如何删除表上的所有默认约束约束

时间:2009-04-20 07:31:08

标签: sql-server sql-server-2005 constraints

如何在SQL 2005中删除属于特定表的所有默认约束?

4 个答案:

答案 0 :(得分:7)

一个解决方案from a search :(编辑为默认约束)

SET NOCOUNT ON

DECLARE  @constraintname SYSNAME, @objectid int,
           @sqlcmd         VARCHAR(1024)

DECLARE CONSTRAINTSCURSOR CURSOR  FOR
SELECT NAME, object_id
FROM   SYS.OBJECTS
WHERE  TYPE = 'D' AND @objectid = OBJECT_ID('Mytable')

OPEN CONSTRAINTSCURSOR

FETCH NEXT FROM CONSTRAINTSCURSOR
INTO @constraintname, @objectid

WHILE (@@FETCH_STATUS = 0)
BEGIN
    SELECT @sqlcmd = 'ALTER TABLE ' + OBJECT_NAME(@objectid) + ' DROP CONSTRAINT ' + @constraintname
    EXEC( @sqlcmd)
    FETCH NEXT FROM CONSTRAINTSCURSOR
    INTO @constraintname, @objectid
END

CLOSE CONSTRAINTSCURSOR
DEALLOCATE CONSTRAINTSCURSOR

答案 1 :(得分:3)

我知道这是旧的,但我只是在谷歌上搜索它。 下面是一个解决方案,它适用于SQL 2008(不确定于2005年)而不依赖于游标:

declare @sql nvarchar(max)

set @sql = ''

select @sql = @sql + 'alter table YourTable drop constraint ' + name  + ';'
from sys.default_constraints 
where parent_object_id = object_id('YourTable')
AND type = 'D'

exec sp_executesql @sql

答案 2 :(得分:0)

gbn发布的脚本对我不起作用,所以我使用的是修改版本:

SET NOCOUNT ON

DECLARE  @DfId INT, @TableId INT,
         @SqlCmd    VARCHAR(1024)

DECLARE DFCONSTRAINTCUR CURSOR FOR
SELECT [parent_object_id] TABLE_ID, [object_id] DF_ID
FROM   SYS.OBJECTS
where parent_object_id = OBJECT_ID('<table name>') 
and [TYPE] = 'D' 

OPEN DFCONSTRAINTCUR

FETCH NEXT FROM DFCONSTRAINTCUR
INTO @TableId, @DfId

WHILE (@@FETCH_STATUS = 0)
BEGIN
    SELECT @sqlcmd = 'ALTER TABLE ' + OBJECT_NAME(@TableId) + ' DROP CONSTRAINT ' + OBJECT_NAME(@DfId)
    EXEC(@sqlcmd)
    FETCH NEXT FROM DFCONSTRAINTCUR
    INTO @TableId, @DfId
END

CLOSE DFCONSTRAINTCUR
DEALLOCATE DFCONSTRAINTCUR

答案 3 :(得分:-1)

你为什么要这样做?删除约束是一项非常激烈的操作,不仅会影响所有用户,还会影响您的流程。也许你的问题可以通过其他方式解决。如果你不是系统的dba,你应该认真考虑是否应该这样做。 (当然在大多数系统中,dba不允许任何其他人获得这样的权限。)