为什么SQL Server会继续创建DF约束?

时间:2011-10-05 15:00:01

标签: sql sql-server sql-server-2008

我正在尝试在SQL中创建升级和回退脚本。升级脚本会添加如下列:

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N'ColumnName' 
    AND object_id = OBJECT_ID(N'[dbo].[TableName]'))

ALTER TABLE TableName
    ADD ColumnName bit NOT NULL DEFAULT(0) 

回退脚本会删除列,如下所示:

IF EXISTS (SELECT * FROM sys.columns WHERE Name = N'ColumnName' 
    AND object_id = OBJECT_ID(N'[dbo].[TableName]'))

ALTER TABLE TableName
    DROP COLUMN ColumnName

但是,回退脚本会抛出此错误:

Msg 5074, Level 16, State 1, Line 5
    The object 'DF__TableName__ColumnName__1BF3D5BD' is dependent on column 'ColumnName'.
Msg 4922, Level 16, State 9, Line 5
    ALTER TABLE DROP COLUMN ColumnName failed because one or more objects access this column.

我知道如何删除约束,但约束的名称每次都会更改(后缀更改)。我要么需要SQL Server来停止创建这个随机命名的约束,要么我需要能够使用通配符字符删除我的脚本中的约束,因为名称会更改。

3 个答案:

答案 0 :(得分:69)

这是由于新添加的列中的default而添加的DEFAULT(0)约束。

您可以自己命名,因此它具有已知的固定名称,而不是依赖于自动生成名称。

ALTER TABLE TableName
    ADD ColumnName bit NOT NULL CONSTRAINT DF_Some_Fixed_Name DEFAULT(0) 

然后一起删除列和约束

ALTER TABLE dbo.TableName
DROP CONSTRAINT DF_Some_Fixed_Name, COLUMN ColumnName

答案 1 :(得分:3)

运行:

declare @name as nvarchar(255);
SELECT @name = name FROM dbo.sysobjects 
WHERE name like 'DF__XXX__YYY__%' and type = 'D'

IF @name is not null BEGIN
    EXEC('ALTER TABLE XXX] DROP CONSTRAINT ' + @name);
END

答案 2 :(得分:1)

如果要删除约束,请运行此命令:

DECLARE @tableName NVARCHAR(255) = '[INSERT]';
DECLARE @first5CharsFromColumnName NVARCHAR(255) = '[INSERT]';
DECLARE @name NVARCHAR(255);
SELECT @name = d.name FROM dbo.sysobjects d
INNER JOIN dbo.sysobjects t ON t.id = d.parent_obj
WHERE d.name LIKE '%'+@first5CharsFromColumnName+'%' AND d.type = 'D' AND t.name = @tableName

IF @name IS NOT NULL BEGIN
    EXEC('ALTER TABLE '+@tableName+' DROP CONSTRAINT ' + @name);
END