是否删除具有非法名称的默认约束



由于名称规范化脚本错误,我有几个默认约束现在具有非法名称(显然sp_rename在验证newname参数方面做得很差(。

某些列具有格式的实际默认名称

[[DF_SomeTable_SomeColumn]] 

[dbo.[DF_SomeOtherDefault]]

sp_renameAlter Table Drop Constraint都不能删除它们,因为它们被报告为语法错误。

如何删除或重命名它们?

最简单的方法可能是让SQL使用quotename函数为您提供正确的转义约束名称。您可以查询目录视图,以便根据表名为您生成drop语句。例如:

-- this weirdness will create a default constraint called [[my weird default]]
create table t(i int constraint [[[my weird default]]]]] default (1))
-- find all the constraints with square bracket literals on the tables I care about
select  concat('alter table [', t.name, '] drop constraint ', quotename(c.name))
from    sys.tables                  t
join    sys.default_constraints c   on  c.parent_object_id = t.object_id
where   t.name = 't'
and     c.name like '%[[]%'

-- returns: alter table [t] drop constraint [[[my weird default]]]]]

显然,要为查询添加适当的筛选。

最新更新