Sql server - 动态更改所有外键约束Update_Rule
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sql server - 动态更改所有外键约束Update_Rule相关的知识,希望对你有一定的参考价值。
我试图通过在数据库中设置为UPDATE_RULE
的'NO ACTION'
来检查所有外键约束,并将该规则更改为'CASCADE'
。所以,我知道我应该首先删除该约束并重新添加它。
为了做到这一点,我尝试了以下查询来获取所有相关的约束,然后迭代每一行并构建一个动态的sql查询,它将删除约束,并将使用不同的UPDATE_RULE
值重新添加它。
但是,为了添加约束,我需要定义主键的表名,我在查询中没有它。我只有外键所在的表名:
SELECT *
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
INNER JOIN INFORMATION_SCHEMA.table_constraints AS CU
ON CU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND CU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE UPDATE_RULE = 'NO ACTION'
有关如何做的任何建议?我只需要更改约束UPDATE_RULE
值。
答案
SELECT
o1.name AS FK_table,
c1.name AS FK_column,
fk.name AS FK_name,
o2.name AS PK_table,
c2.name AS PK_column,
pk.name AS PK_name,
fk.delete_referential_action_desc AS Delete_Action,
fk.update_referential_action_desc AS Update_Action
FROM sys.objects o1
INNER JOIN sys.foreign_keys fk
ON o1.object_id = fk.parent_object_id
INNER JOIN sys.foreign_key_columns fkc
ON fk.object_id = fkc.constraint_object_id
INNER JOIN sys.columns c1
ON fkc.parent_object_id = c1.object_id
AND fkc.parent_column_id = c1.column_id
INNER JOIN sys.columns c2
ON fkc.referenced_object_id = c2.object_id
AND fkc.referenced_column_id = c2.column_id
INNER JOIN sys.objects o2
ON fk.referenced_object_id = o2.object_id
INNER JOIN sys.key_constraints pk
ON fk.referenced_object_id = pk.parent_object_id
AND fk.key_index_id = pk.unique_index_id
ORDER BY o1.name, o2.name, fkc.constraint_column_id
以上是关于Sql server - 动态更改所有外键约束Update_Rule的主要内容,如果未能解决你的问题,请参考以下文章