有时候我们在drop column的时候,会遇到一些default constraints而不能drop,如果我们已经知道constraint name,则可以用下面的语句先把constraint remove掉,然后再drop column。
declare @sql nvarchar(1024) set @sql = N'alter table [system] drop constraint DF_system_LastGraceDate' exec sp_executesql @sql
如果我们不知道constraint name,我们可以先把他们找出来,然后再remove掉。
-- first define variables declare @default sysname, @sql nvarchar(max) -- get name of default constraint select @default = name from sys.default_constraints where parent_object_id = object_id('TABLE_NAME') AND type = 'D' AND parent_column_id = ( select column_id from sys.columns where object_id = object_id('TABLE_NAME') and name = 'COLUMN_NAME' ) -- create alter table command as string and run it set @sql = N'alter table TABLE_NAME drop constraint ' + @default exec sp_executesql @sql