在 SQL Server 中,您可以使用以下方法对按外键依赖关系排序的表名进行排序:
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
和 INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
视图获取外键关系信息。以下是一个示例查询,它将返回当前数据库中按外键依赖关系排序的表名列表:
WITH RECURSIVE FK_Sort AS (
SELECT
TC.TABLE_NAME,
TC.CONSTRAINT_NAME,
RCON.UNIQUE_CONSTRAINT_NAME,
RCON.UNIQUE_CONSTRAINT_CATALOG,
RCON.UNIQUE_CONSTRAINT_SCHEMA,
RCON.UNIQUE_CONSTRAINT_TABLE_NAME,
1 AS LEVEL
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RCON ON TC.CONSTRAINT_NAME = RCON.CONSTRAINT_NAME
WHERE
TC.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND TC.TABLE_CATALOG = 'YourDatabase'
AND NOT EXISTS (
SELECT
*
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC2
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RCON2 ON TC2.CONSTRAINT_NAME = RCON2.CONSTRAINT_NAME
WHERE
TC2.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND TC2.TABLE_CATALOG = 'YourDatabase'
AND RCON2.UNIQUE_CONSTRAINT_CATALOG = TC.TABLE_CATALOG
AND RCON2.UNIQUE_CONSTRAINT_SCHEMA = TC.TABLE_SCHEMA
AND RCON2.UNIQUE_CONSTRAINT_TABLE_NAME = TC.TABLE_NAME
)
UNION ALL
SELECT
TC.TABLE_NAME,
TC.CONSTRAINT_NAME,
RCON.UNIQUE_CONSTRAINT_NAME,
RCON.UNIQUE_CONSTRAINT_CATALOG,
RCON.UNIQUE_CONSTRAINT_SCHEMA,
RCON.UNIQUE_CONSTRAINT_TABLE_NAME,
FKS.LEVEL + 1 AS LEVEL
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RCON ON TC.CONSTRAINT_NAME = RCON.CONSTRAINT_NAME
INNER JOIN FK_Sort AS FKS ON FKS.TABLE_NAME = RCON.UNIQUE_CONSTRAINT_TABLE_NAME
WHERE
TC.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND TC.TABLE_CATALOG = 'YourDatabase'
)
SELECT
TABLE_NAME,
LEVEL
FROM
FK_Sort
ORDER BY
LEVEL ASC;
请注意,您需要将 YourDatabase
替换为您要查询的实际数据库名称。
此查询将返回一个按外键依赖关系排序的表名列表,其中每个表名后面都有一个表示其依赖关系级别的数字。级别越低,表的依赖关系越深。
请注意,此查询仅适用于 SQL Server 2012 及更高版本。如果您使用的是较旧版本的 SQL Server,则可能需要使用不同的方法来获取外键关系信息。
领取专属 10元无门槛券
手把手带您无忧上云