sql server 中删除默认约束的通用sql脚本(轉)

在SQL Server 中,如果给表的一个字段设置了默认值,就会在系统表sysobjects中生成一个默认约束。
如果想删除这个设置了默认值的字段(假设此字段名column1),执行“ALTER TABLE table1 DROP COLUMN column1”时就会报错:

The object 'DF__xxxxxxxxxxx' is dependent on column 'column1'. 
ALTER TABLE DROP COLUMN column1failed because one or more objects access this column.




所以在删除此字段时需要先将系统表中的对应默认约束删除, 可以使用下面的脚本进行删除:

-- 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 
inner 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)
set @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname
if @cmd is null print 'No default constraint to drop'
exec (@cmd)



在删除对应的默认约束后,执行:

ALTER TABLE table1 DROP COLUMN column1



即可删除字段。

你可能感兴趣的:(sql,sql,server,脚本,Access)