sql server外键如果不合我们的心意,能不能进行重命名呢?答案是肯定的。下文的例子就将为您示范sql server外键如何进行重命名,供您参考。
本实例的数据库原先是采用PowerDesigner设计的,那些外键约束的命名非常难看,并且也和后来在SSMS中额外添加的外键约束命名规则不一致,因此就像遍历数据库的所有外键约束,找到外键约束的相关对象,然后重新生成一致的命名。
采用的命名规则是:
- FK_ForeignTable_PrimaryTable_On_ForeignColumn
直白的翻译就是,ForeignTable在ForeignColumn列上引用了PrimaryTable的主键。
Sql Server提供了很多动态管理视图(Dynamic management views,DMV)和存储过程,方便我们对数据库进行维护。这里我用到了以下两个sys.foreign_key_columns(包含外键约束完整信息)和sys.objects(数据库对象信息)这两个DMV以及sp_rename执行重命名的系统存储过程。代码如下:
- 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
【编辑推荐】