有时候我们在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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-24
  • 2022-02-21
  • 2022-12-23
  • 2021-12-07
猜你喜欢
  • 2021-04-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案