How do I drop a column with object dependencies in SQL Server 2008? - sql

The error message I'm obtaining when trying to drop a column:
The object 'defEmptyString' is dependent on column 'fkKeywordRolleKontakt'.
Msg 5074, Level 16, State 1, Line 43
ALTER TABLE DROP COLUMN fkKeywordRolleKontakt failed because one or more objects access this column.
I have already tried to find the default constraints, as described here:
SQL Server 2005 drop column with constraints
Unfortunately without any success :( The line returned is:
fkKeywordRolleKontakt 2 814625945 0 defEmptyString
And I cannot remove either of fkKeywordRolleKontakt and defEmptyString.
What is the correct way to get rid of this dependency?
EDIT: Perhaps this is of importance too. The column fkKeywordRolleKontakt is of type udKeyword (nvarchar(50)) with default dbo.defEmptyString.
Edit 2: Solved
I could solve the problem now. I'm sorry, I did not copy the full error message, which was:
Msg 5074, Level 16, State 1, Line 1
The object 'defEmptyString' is dependent on column 'fkKeywordRolleKontakt'.
Msg 5074, Level 16, State 1, Line 1
The object 'FK_tlkpRolleKontakt_tlkpKeyword' is dependent on column 'fkKeywordRolleKontakt'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN fkKeywordRolleKontakt failed because one or more objects access this column.
I could generate a script to drop the column by right-clicking on the column entry (dbo.tlkpRolleKontakt > Columns > fkKeywordRolleKontakt) (in MSSQL Server Manager), selecting Modify and deleting the column. Then Table Designer > Generate Change Script generated the necessary commands:
ALTER TABLE dbo.tlkpRolleKontakt
DROP CONSTRAINT FK_tlkpRolleKontakt_tlkpKeyword
EXECUTE sp_unbindefault N'dbo.tlkpRolleKontakt.fkKeywordRolleKontakt'
ALTER TABLE dbo.tlkpRolleKontakt
DROP COLUMN fkKeywordRolleKontakt
That's it :)

Did you try first:
ALTER TABLE <tablename> DROP CONSTRAINT defEmptyString;
?

drop the constraint which is dependent on that column with
ALTER TABLE TableName DROP CONSTRAINT dependent_constraint
Then Drop Column:
ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME
dependent_constraint : this constraint is shown in the error when we try to delete dependent column.
Example: trying to drop some column IsDeleted2
Error
The object 'DF__Employees__IsDel__15502E78' is dependent on column
'IsDeleted2'.
ALTER TABLE DROP COLUMN IsDeleted2 failed because one or more objects
access this column.
Error clearly states that we need to delete DF__Employees__IsDel__15502E78 constraint
ALTER TABLE Employess
DROP CONSTRAINT DF__Employees__IsDel__15502E78;
Drop Column: ALTER TABLE Employess DROP COLUMN IsDelted2

I could solve the problem now. I'm sorry, I did not copy the full error message, which was:
Msg 5074, Level 16, State 1, Line 1
The object 'defEmptyString' is dependent on column 'fkKeywordRolleKontakt'.
Msg 5074, Level 16, State 1, Line 1 The object
'FK_tlkpRolleKontakt_tlkpKeyword' is dependent on column
'fkKeywordRolleKontakt'. Msg 4922, Level 16, State 9, Line 1 ALTER TABLE DROP COLUMN fkKeywordRolleKontakt failed because one or
more objects access this column.
I could generate a script to drop the column by right-clicking on the column entry (dbo.tlkpRolleKontakt > Columns > fkKeywordRolleKontakt) (in MSSQL Server Manager), selecting Modify and deleting the column. Then Table Designer > Generate Change Script generated the necessary commands:
ALTER TABLE dbo.tlkpRolleKontakt
DROP CONSTRAINT FK_tlkpRolleKontakt_tlkpKeyword
EXECUTE sp_unbindefault N'dbo.tlkpRolleKontakt.fkKeywordRolleKontakt'
ALTER TABLE dbo.tlkpRolleKontakt
DROP COLUMN fkKeywordRolleKontakt

use this script to cancel the checking of constraint :
ALTER TABLE #tablename NOCHECK CONSTRAINT #constraintname

I ran into a simpler solution.
DELETE the data of that column.
Once the column has no value inside it do -
ALTER TABLE <table_name> DROP COLUMN <column_name>
This way the column is easily dropped.
P.S - This is a headache if you have like extreme amounts of data in the column.

Related

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.

Alter Field Type from nvarchar(255) to nvarchar(Max) in SQL Server 2005

I would like to alter column type in table stk020. So, I used this query..
ALTER TABLE [stk020]
ALTER COLUMN [t16] nvarchar(Max) not null
The original column type of [t16] is nvarchar(255). I get this error
Msg 5074, Level 16, State 1, Line 1
The object 'DF_STK020_t16__725CC34D' is dependent on column 't16'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN t16 failed because one or more objects access this column.
Any solution?
You must first drop what we presume is the Default constraint on the column before you alter its data type:
Alter Table stk020 Drop Constraint DF_STK020_t16__725CC34D
GO
Alter Table stk020 Alter Column t16 nvarchar(max) not null
GO
Alter Table stk020 Add Constraint DF_STK020_t16__725CC34D
Default ... For t16

Msg 5074, Level 16, State 1, Line 1 The index 'IX_Alias_Alias' is dependent on column 'Alias'

Want to change the collation
using the below script
ALTER TABLE Alias ALTER COLUMN Alias nvarchar(25) COLLATE SQL_Latin1_General_CP1256_CI_AS
Error occurs
Msg 5074, Level 16, State 1, Line 1
The index 'IX_Alias_Alias' is dependent on column 'Alias'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN Alias failed because one or more objects access this column.
Actually I want to change the collation of all the table in database
You can use the below link to alter the collation of all the objects in a database.
Alter Collation for all the objects in a DB
You should delete the index first and then modify the column.