在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
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)
在删除对应的默认约束后,执行:
ALTER TABLE table1 DROP COLUMN column1
即可删除字段。
阅读(1452) | 评论(0) | 转发(0) |