SQL Server中對應(yīng)默認(rèn)約束的刪除方法
下面將為您介紹在SQL Server中將系統(tǒng)表中的對應(yīng)默認(rèn)約束刪除的腳本,供您參考,希望對您能夠有所啟迪。
在SQL Server 中,如果給表的一個(gè)字段設(shè)置了默認(rèn)值,就會在系統(tǒng)表sysobjects中生成一個(gè)默認(rèn)約束。
如果想刪除這個(gè)設(shè)置了默認(rèn)值的字段(假設(shè)此字段名column1),
執(zhí)行“ALTER TABLE table1 DROP COLUMN column1”時(shí)就會報(bào)錯(cuò):
The object 'DF__xxxxxxxxxxx' is dependent on column 'column1'.
ALTER TABLE DROP COLUMN column1failed because one or more objects access this column.
所以在刪除此字段時(shí)需要先將系統(tǒng)表中的對應(yīng)默認(rèn)約束刪除, 可以使用下面的腳本進(jìn)行刪除:
-- this script drops the default constraint which is generated by the setting of default value.
DECLARE @tablename VARCHAR(100), @columnname VARCHAR(100), @tab VARCHAR(100)
SET @tablename='CountryGroupEmailAndWaitAux'
SET @columnname='actionOfHasNoValidEmail'
declare @defname varchar(100)
declare @cmd varchar(100)
select @defname = name
FROM sysobjects so
JOIN sysconstraints sc
ON so.id = sc.constid
WHERE object_name(so.parent_obj) = @tablename
AND so.xtype = 'D'
AND sc.colid =
(SELECT colid FROM syscolumns
WHERE id = object_id(@tablename) AND
name = @columnname)
select @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname
if @cmd is null print 'No default constraint to drop'
exec (@cmd)
在刪除對應(yīng)的默認(rèn)約束后,執(zhí)行:
ALTER TABLE table1 DROP COLUMN column1
即可刪除字段。
【編輯推薦】
刪除SQL約束的方法