如何在数据库中查询所有类型的约束,例如主键,外键,唯一键和默认约束,并将其系统生成名称重命名为以下格式的名称:
答案 0 :(得分:1)
SELECT tbl.name TableName, col.name ColName, ck.name ConstraintName, ck.definition ConstraintDefinition ,' exec sp_rename [' +ck.name + '] , [DF_' + col.name + ']' SqlQuery
FROM sys.default_constraints ck
INNER JOIN sys.tables tbl
on ck.parent_object_id = tbl.object_id
INNER JOIN sys.columns col
on tbl.object_id = col.object_id
and ck.parent_column_id = col.column_id
这是默认约束
使用sys.key_constraints ans sys.foreign_keys
答案 1 :(得分:0)
以下代码更加详细,它也特定于默认约束。
select quotename(s.name) + '.' + quotename(o.name) as table_name,
dc.name as default_name,
'DF_' + o.name + '_' + c.name as new_default_name,
'execute sp_rename ''' + quotename(s.name) + '.' + dc.name + ''', ''' + 'DF_' + o.name + '_' + c.name + ''' , ''OBJECT'' -- ' + s.name + '.' + o.name + '' as rename_script
from sys.default_constraints as dc
join sys.objects as o
join sys.schemas as s
on o.schema_id = s.schema_id
on o.object_id = dc.parent_object_id
join sys.columns as c
on o.object_id = c.object_id
and c.column_id = dc.parent_column_id
where dc.name like 'DF[_][_]%[_][_]%[_][_]%' -- DF__AlertType__Creat__10F7245D
and o.type = 'u'
and o.is_ms_shipped = 0
order by s.name,
o.name