Sql server - 动态更改所有外键约束Update_Rule

时间:2017-12-21 10:16:31

标签: sql-server foreign-keys constraints

我正在尝试检查数据库中UPDATE_RULE设置为'NO ACTION'的所有外键约束,并将该规则更改为'CASCADE'。 所以,我知道我应该首先删除该约束并重新添加它。

为了做到这一点,我尝试了以下查询来获取所有相关约束,然后迭代每一行并构建一个动态sql查询,这将删除约束,并将使用不同的{{重新添加它1}}值。

但是,为了添加约束,我需要定义主键的表名,我的查询中没有。我只有外键所在的表名:

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' 值。

1 个答案:

答案 0 :(得分:0)

答案在这里找到: https://dba.stackexchange.com/questions/31720/find-the-foreign-keys-associated-with-a-given-primary-key

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