我想创建一个用于测试目的的数据子集,我从一个用户表开始,选择 a 类型的 X、b 类型的 Y、c 类型的 Z(等等),然后创建一个包含这些的新表用户。然后我需要创建所有相关表(带有必要的记录),然后创建所有相关表...
我相当确定最好的方法是递归公用表表达式,但是我对这些没有太多经验,希望有人能帮助我。到目前为止,我有以下内容,但注意到两件事:
- 2 级似乎包含了 1 级中的所有内容,除了我期望的新记录
这实际上并没有创建/插入记录(我仍然需要帮助)
WITH cte AS ( SELECT DISTINCT fk.object_id, fk.schema_id, fk.parent_object_id, fc.parent_column_id, t.schema_id AS referenced_schema_id, fk.referenced_object_id, ic.column_id AS referenced_column_id, 1 AS Level FROM sys.foreign_keys fk INNER JOIN sys.tables t ON fk.referenced_object_id = t.object_id INNER JOIN sys.foreign_key_columns fc ON fk.object_id = fc.constraint_object_id INNER JOIN sys.indexes i ON fk.referenced_object_id = i.object_id AND i.is_primary_key = 1 INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id WHERE fk.type = 'F' AND fk.referenced_object_id = OBJECT_ID(N'dbo.Users', N'U') UNION ALL SELECT fk.object_id, fk.schema_id, fk.parent_object_id, fc.parent_column_id, t.schema_id, fk.referenced_object_id, ic.column_id AS referenced_column_id, cte.Level + 1 FROM sys.foreign_keys fk INNER JOIN sys.tables t ON fk.referenced_object_id = t.object_id INNER JOIN sys.foreign_key_columns fc ON fk.object_id = fc.constraint_object_id INNER JOIN sys.indexes i ON fk.referenced_object_id = i.object_id AND i.is_primary_key = 1 INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id INNER JOIN cte ON fk.referenced_object_id = cte.parent_object_id WHERE fk.type = 'F' AND fk.parent_object_id <> cte.referenced_object_id ), cteHierarchy AS ( SELECT DISTINCT OBJECT_NAME(cte.object_id) AS ReferringKey, SCHEMA_NAME(cte.schema_id) AS ReferringSchema, OBJECT_NAME(cte.parent_object_id) as ReferringTable, COL_NAME(cte.parent_object_id,cte.parent_column_id) ReferringColumn, SCHEMA_NAME(cte.referenced_schema_id) AS ReferencedSchema, OBJECT_NAME(cte.referenced_object_id) as ReferencedTable, COL_NAME(cte.referenced_object_id,cte.referenced_column_id) ReferencedColumn, Level FROM cte ) SELECT * FROM cteHierarchy ORDER BY Level, ReferencedSchema, ReferencedTable, ReferringTable;
谢谢您的帮助!