Alma
Alma

Reputation: 4410

Delete a SQL Table Column give Constraint dependency error

I try to drop a column in SQL but I am getting this error:

The object 'DF__...'is dependent on column ... 

I found a lot of solutions that need to drop the Constraint first, so I ran this and worked:

ALTER TABLE [dbo].[Configuration] DROP CONSTRAINT DF__SiteConfi__Na__2DFCAC08;
ALTER TABLE [dbo].[Configuration] DROP COLUMN NaFlag;

But I need this script to run on any server, so I don't want to mention the Constraint name as it may be different on any other servers. What is the best solution?

Upvotes: 0

Views: 827

Answers (2)

Jorge Bugal
Jorge Bugal

Reputation: 439

You can use some dynamic SQL to drop the default. If it's an isolated script to just drop the column, then it's easier, something like:

DECLARE @sqlDF NVARCHAR(MAX);
SELECT @sqlDF = 'ALTER TABLE {$tableName} DROP CONSTRAINT ' + QUOTENAME(OBJECT_NAME([default_object_id])) + ';'
FROM sys.columns
WHERE [object_id] = OBJECT_ID('{$tableName}') AND [name] in ({$columns}) AND [default_object_id] <> 0;

IF @sqlDF IS NOT NULL
    EXEC(@sqlDF);

If you are working with a migrations tool, maybe you're gonna have to refactor this, so it doesn't try to redeclare the @sqlDF variable.

Upvotes: 1

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89316

Here's a query to get you started:

with q as
(
    select schema_name(t.schema_id) schema_name,
           t.name table_name,
           c.name column_name,
           d.name default_name
    from sys.tables t
    join sys.columns c
      on t.object_id = c.object_id
    join sys.default_constraints d
      on d.parent_object_id = t.object_id
     and d.parent_column_id = c.column_id
 )
select concat(
        'alter table ',
        quotename(schema_name),'.',quotename(table_name),
        ' drop constraint ', quotename(default_name) ) sql
from q

Upvotes: 0

Related Questions