TSQL:获取受级联删除影响的所有表

TSQL: Get all tables affected by Cascade Delete

我正在寻找一个 SQL 脚本,它将列出从 table X 中删除记录时将受到影响的所有 table。 它还应该在“树”中列出受影响的相关 tables,因为受影响的 tables 将对其他人进行级联删除,这反过来又会影响其他人等

-- using sys tables to enumerate foreign keys
    SELECT
        f.name constraint_name
       ,OBJECT_NAME(f.parent_object_id) referencing_table_name
       ,COL_NAME(fc.parent_object_id, fc.parent_column_id) referencing_column_name
       ,OBJECT_NAME (f.referenced_object_id) referenced_table_name
       ,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) referenced_column_name
       ,delete_referential_action_desc
       ,update_referential_action_desc
    FROM sys.foreign_keys AS f
    INNER JOIN sys.foreign_key_columns AS fc
       ON f.object_id = fc.constraint_object_id
    ORDER BY f.name

您可以使用递归 CTE 生成受影响表的完整层次结构,例如

WITH OnDelete AS
(   SELECT f.parent_object_id,
            f.referenced_object_id,
            RecursionLevel = 1,
            ObjectTree = CONVERT(VARCHAR(MAX), CONCAT(OBJECT_NAME(f.parent_object_id), ' --> ', OBJECT_NAME(f.referenced_object_id)))
    FROM sys.foreign_keys AS f
    WHERE f.delete_referential_action_desc = 'CASCADE'
    UNION ALL
    SELECT  od.parent_object_id,
            f.referenced_object_id,
            od.RecursionLevel + 1,
            ObjectTree = CONVERT(VARCHAR(MAX), CONCAT(od.ObjectTree, ' --> ', OBJECT_NAME(f.referenced_object_id)))
    FROM    OnDelete AS od
            INNER JOIN sys.foreign_keys AS f
                ON f.parent_object_id = od.referenced_object_id
                AND f.delete_referential_action_desc = 'CASCADE'

)
SELECT  BaseTable = OBJECT_NAME(od.parent_object_id),
        OnDelete = od.ObjectTree
FROM    OnDelete AS od
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    OnDelete AS ex
            WHERE   ex.parent_object_id = od.parent_object_id
            AND     ex.ObjectTree LIKE CONCAT(od.ObjectTree, '%')
            AND     LEN(ex.ObjectTree) > LEN(od.ObjectTree)
        )
ORDER BY od.parent_object_id;

这将输出如下内容:

BaseTable OnDelete
T2 T2 --> T1
T3 T3 --> T2 --> T1
T4 T4 --> T3 --> T2 --> T1
T5 T5 --> T4 --> T3 --> T2 --> T1

Example on db<>fiddle