我想对多个数据库中的列施加约束。我不知道列上约束的确切名称。
是否有可能在不知道约束名称的情况下删除约束。
例如: 如果列名上存在ALTER TABLE TempTable DROP约束
答案 0 :(得分:1)
您可以从像这样的表中检索约束信息
select t.Name as TableName,
ccd.Name as ColumnName_default_constraint,
dc.Name as default_constraint,
ccc.Name as ColumnName_check_constraint,
cc.Name as check_constraint
from sys.tables t
inner join sys.default_constraints dc on t.object_id = dc.parent_object_id
inner join sys.check_constraints cc on t.object_id = cc.parent_object_id
inner join sys.columns ccd on dc.parent_object_id = ccd.object_id
and ccd.column_id = dc.parent_column_id
inner join sys.columns ccc on cc.parent_object_id = ccc.object_id
and ccc.column_id = cc.parent_column_id
where t.Name = 'your table name'
order by t.Name
由此您可以构建这样的脚本
select 'alter table ' + t.Name +' drop constraint ' + dc.Name,
'alter table ' + t.Name +' drop constraint ' + cc.Name
from sys.tables t
inner join sys.default_constraints dc on t.object_id = dc.parent_object_id
inner join sys.check_constraints cc on t.object_id = cc.parent_object_id
where t.Name = 'your table name'
order by t.Name