Alter table error massage in any changes in particular database - sql

CREATE TABLE production.product_colors (
color_id INT PRIMARY KEY IDENTITY,
color_name VARCHAR (50) NOT NULL,
created_at DATETIME2
);
I created table production,product_colors and column name created_at datetime2 data type and now I want change data type but I cannot. Not only one table, I cannot alter any table in the database.
ALTER TABLE production.product_colors
ADD CONSTRAINT df_current_time
DEFAULT CURRENT_TIMESTAMP FOR created_at;
When I am running above query I get this error:
Msg 208, Level 16, State 1, Procedure TR_ALTERTABLE, Line 6 [Batch Start Line 86]
Invalid object name 'TableSchemaChanges'.
I cannot understand why this error occurring. I searched google and nothing helps me.

I think the issue caused by schema. Please double-check it.
Here is a correct sample using 'dbo' schema.
Demo
Please refer to the documentation
The following example creates a DDL trigger safety with database scope, and then disables and enables it.
CREATE TRIGGER safety
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You must disable Trigger "safety" to drop or alter tables!'
ROLLBACK;
GO
DISABLE TRIGGER safety ON DATABASE;
GO
ENABLE TRIGGER safety ON DATABASE;
GO

Related

My INSERT statement conflicted with the FOREIGN KEY constraint

enter image description here
Those are my diagrams - I create procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[hasta]
#Ad nchar(50),
#Soyadı nvarchar(100),
#TcKimlik nchar(11),
#DogumTarihi varchar(8),
#TelefonNo nvarchar(11)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].Hastalar ([Ad], [Soyadı], [TcKimlik], [DogumTarihi], [TelefonNo])
VALUES (#Ad, #Soyadı, #TcKimlik, #DogumTarihi, #TelefonNo)
END
After I want add data in Hastalar table, I write
exec hasta 'Emir','Yılmaz','35635993564','1995.11.19','05347331085'
but I get this error
Msg 547, Level 16, State 0, Procedure hasta, Line 13
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Hastalar_Testler". The conflict occurred in database "hastane", table "dbo.Testler", column 'TestID'. The statement has been terminated.
In your table [dbo].Hastalar, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help '[dbo].Hastalar'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.
What part of the error do you not understand?
The message is saying that one of the columns -- "TestId" -- is referring to another table. And the value being inserted is not already in that table.
You are not explicitly inserting a value for TestId, so that value is being set using a default constraint or trigger. I would suggest that you explicit provide the value in the insert -- even if that value is NULL.

Error in changing column length in Postgres

I am trying to change the column size from 100 to 150 varchar data type using following query:
alter table data_warehouse.tbl_abc
alter column first_nm varchar(150) null;
Getting the following error:
SQL Error [42601]: ERROR: syntax error at or near "varchar"
Position: 77
The syntax is a bit different, so try this:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm type varchar(120);
The error in your syntax is that you missed a TYPE keyword:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150);
and if you have a NOT NULL constraint you want to remove, add a new ALTER COLUMN inside the same ALTER TABLE statement:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150),
ALTER COLUMN first_nm DROP NOT NULL;
for reference look here: https://www.postgresql.org/docs/current/sql-altertable.html
Edit: as in the comment, if you have a view which involves the same column, drop it and re-create it under transaction:
BEGIN TRANSACTION;
DROP VIEW [...];
ALTER TABLE [...];
CREATE VIEW [...];
COMMIT;
Be aware that to alter a table, you must acquire an exclusive lock on it, so during the whole process, all the queries over the same table and on the views of the table are locked, also if they don't read from the altered column (because the whole table is locked) - use with caution in production environment

Changing column Datatype from date to datetime without removing existing values in MSSql and Oracle sql server [duplicate]

I am trying to do this:
ALTER TABLE CompanyTransactions DROP COLUMN Created
But I get this:
Msg 5074, Level 16, State 1, Line 2
The object 'DF__CompanyTr__Creat__0CDAE408' is dependent on column 'Created'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE DROP COLUMN Created failed because one or more objects access this column.
This is a code first table. Somehow the migrations have become all messed up and I am trying to manually roll back some changed.
I have no idea what this is:
DF__CompanyTr__Creat__0CDAE408
You must remove the constraints from the column before removing the column. The name you are referencing is a default constraint.
e.g.
alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
alter table CompanyTransactions drop column [Created];
The #SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column
ALTER TABLE MySchema.MyTable ADD
MyColumn int DEFAULT NULL;
But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.
So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:
ALTER TABLE MySchema.MyTable ADD
MyColumn int NULL,
CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;
You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.
As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.
Perform followings steps to do the needful.
Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name>
drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc
When you alter column datatype you need to change constraint key for every database
alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
You need to do a few things:
You first need to check if the constrain exits in the information schema
then you need to query by joining the sys.default_constraints and sys.columns
if the columns and default_constraints have the same object ids
When you join in step 2, you would get the constraint name from default_constraints. You drop that constraint. Here is an example of one such drops I did.
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TABLE_NAME'
AND COLUMN_NAME = N'LOWER_LIMIT')
BEGIN
DECLARE #sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
SELECT TOP 1 #sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
FROM sys.default_constraints dc
JOIN sys.columns c
ON c.default_object_id = dc.object_id
WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
IF ##ROWCOUNT = 0
BEGIN
PRINT 'DELETED Constraint on column LOWER_LIMIT'
BREAK
END
EXEC (#sql)
END;
ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
PRINT 'DELETED column LOWER_LIMIT'
END
ELSE
PRINT 'Column LOWER_LIMIT does not exist'
GO
In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:
Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");
You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.
I had the same problem and this was the script that worked for me with a table with a two part name separated by a period ".".
USE [DATABASENAME]
GO
ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9]
GO
ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName]
GO
I needed to replace an INT primary key with a Guid. After a few failed attempts, the EF code below worked for me. If you hyst set the defaultValue... you end up with a single Guid a the key for existing records.
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropUniqueConstraint("PK_Payments", "Payments");
migrationBuilder.DropColumn(
name: "PaymentId",
table: "Payments");
migrationBuilder.AddColumn<Guid>(
name: "PaymentId",
table: "Payments",
type: "uniqueidentifier",
defaultValueSql: "NewId()",
nullable: false);
}
Copy the default constraint name from the error message and type it in the same way as the column you want to delete.
I had the same problem, I could not remove migrations, it would show error that something is already applied, so i changed my DB name in appsettings, removed all migrations, and then added new migration and it worked. Dont understand issue completely, but it worked
I fixed by Adding Dropping constraint inside migration.
migrationBuilder.DropForeignKey(
name: "FK_XX",
table: "TableX").
and below recreates constraint.
migrationBuilder.AddForeignKey(
name: "FK_XX",
table: "TableX",
column: "ColumnX",
onDelete: ReferentialAction.Restrict);

SQL Server 2012 - Queries working executed one on one, but not in a group

I have been trying to execute these two queries together:
ALTER TABLE afm.owned_properties_rpt_table
ALTER COLUMN bl_id CHAR(8) NOT NULL;
ALTER TABLE afm.owned_properties_rpt_table
ADD CONSTRAINT owned_properties_rpt_table_PK PRIMARY KEY (bl_id);
But I'm getting this error:
Mens. 8111, Nivel 16, Estado 1, Línea 3
Cannot define PRIMARY KEY constraint on nullable column in table
'owned_properties_rpt_table'.
Mens. 1750, Nivel 16, Estado 0, Línea 3
Could not create constraint. See previous errors.
It seems that somehow, the second line is being executed before the first one finishes.
I have tried changing semicolons by goes, using a begin transaction/commit transaction structure, and creating an auxiliary column where I copied the data in bl_id and then dropped the old column, all of them without success.
The SQL script needs to be executed on a client's server (where I can not intervene), so dividing the code is not an alternative.
I am sorry if I am missing something elementary, I have also searched for the same problem during several hours without success.
Thanks for your help.
Try this
ALTER TABLE afm.owned_properties_rpt_table ALTER COLUMN bl_id CHAR(8) NOT NULL default 'sometest';
GO
ALTER TABLE afm.owned_properties_rpt_table ADD CONSTRAINT owned_properties_rpt_table_PK PRIMARY KEY (bl_id);

Change length of column of table which have dependencies

I've got a table named Contacts with column Title varchar(50) . Now in the middle of development I want to change the length to varchar(100) of field Title .At the moment table Contacts has over 25 dependencies (other tables, views functions).
When I run following sql statement in sql server 2008 . I am getting errors.
ALTER TABLE [Contacts ] ALTER COLUMN [Title ] varchar(100)
Error Like
Msg 5074, Level 16, State 1, Line 2
The object 'Contacts_title' is dependent on column 'title'.
And more.
you have to drop are recreate the constrains on the Contact table to do that or (sometime not really recommended ) you can temporary disable the constrain, alter the length and enable them again
--disable all constraints for the Sales.SalesOrderHeader table
ALTER TABLE [yourtable] NOCHECK CONSTRAINT ALL
--do your stuff
--do something --enable all constraints for the Sales.SalesOrderHeader table
ALTER TABLE [yourtable] CHECK CONSTRAINT ALL
You have to remove the dependence, and then create it again.