use [database]
go
declare fkcur cursor for
select
OBJECT_NAME(col.constraint_object_id) as FKConstraintName
,fkTable.name as FKTable
,fkCol.name as FKColumn
,pkTable.name as PKTable
,pkCol.name as PKColumn
from sys.foreign_key_columns col
-- 外键约束是建立在外键表上的,
-- 因此foreign_key_columns表中的parent_object_id和parent_column_id分别表示外键表和外键列
inner join sys.objects fkTable
on fkTable.object_id = col.parent_object_id
inner join sys.columns fkCol
on fkCol.column_id = col.parent_column_id
and fkCol.object_id = fkTable.object_id
-- foreign_key_columns表中的referenced_object_id和referenced_column_id分别指向
-- 外键约束的主键表对象以及主键列
inner join sys.objects pkTable
on pkTable.object_id = col.referenced_object_id
inner join sys.columns pkCol
on pkCol.column_id = col.referenced_column_id
and pkCol.object_id = pkTable.object_id
order by OBJECT_NAME(col.constraint_object_id)
open fkcur
declare @constraintName nvarchar(128)
declare @fkTable nvarchar(64)
declare @fkColumn nvarchar(64)
declare @pkTable nvarchar(64)
declare @pkColumn nvarchar(64)
declare @newConstraintName nvarchar(128)
fetch next from fkcur
into @constraintName,@fkTable,@fkColumn,@pkTable,@pkColumn
while @@FETCH_STATUS = 0
begin
set @newConstraintName = 'FK_'+@fkTable+'_'+@pkTable+'_On_'+@fkColumn
exec sp_rename @constraintName,@newConstraintName,'Object'
fetch next from fkcur
into @constraintName,@fkTable,@fkColumn,@pkTable,@pkColumn
end
close fkcur
deallocate fkcur