由于名称规范化脚本错误,我有几个默认约束现在具有非法名称(显然sp_rename
在验证newname
参数方面做得很差(。
某些列具有格式的实际默认名称
[[DF_SomeTable_SomeColumn]]
或
[dbo.[DF_SomeOtherDefault]]
sp_rename
和Alter 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]]]]]
显然,要为查询添加适当的筛选。