1

如何构建查询以按外键依赖顺序获取 SQL Server 中的表名?

如果有一个表 XYZ,它是主表,其他 2 个表具有外键约束,那么我希望表 XYZ 首先出现。

这是为了能够以正确的顺序创建表。

4

3 回答 3

0

此查询将按其依赖顺序返回表:

     ;WITH vwTableDependancy AS (
        SELECT 
            tables.object_id Dependant , NULL Parent
        FROM 
            sys.tables
        LEFT OUTER JOIN
            sys.foreign_keys
        ON
            foreign_keys.parent_object_id = tables.object_id
        WHERE
            foreign_keys.parent_object_id IS NULL
        UNION    
        SELECT 
            parent_object_id Dependant, referenced_object_id Parent
        FROM 
            sys.foreign_keys
    )
    , vwTableHierarchy AS (
        SELECT Dependant,Parent, 0 lvl FROM vwTableDependancy WHERE Parent IS NULL
        UNION ALL
        SELECT 
            vwTableDependancy.Dependant,vwTableDependancy.Parent , lvl+1
        FROM 
            vwTableDependancy 
        INNER JOIN
            vwTableHierarchy
        ON
            vwTableDependancy.Parent = vwTableHierarchy.Dependant
    )
    SELECT 
         OBJECT_NAME(Dependant) Dependant
        ,OBJECT_NAME(Parent) Parent
        , lvl  
    FROM 
        vwTableHierarchy
    ORDER BY 
        lvl ASC
    OPTION(MAXRECURSION 0)
于 2012-11-01T16:14:17.953 回答
0
select * from sys.tables st
join sys.foreign_keys sfk on st.object_id = sfk.parent_object_id 
where sfk.name = 'Foreign_Key'
于 2015-10-14T18:19:10.710 回答
-2

您可以在下表中找到所需的信息:

select * from sys.tables
select * from sys.foreign_keys
select * from sys.foreign_key_columns

从那里,构建将按照您的需要执行的脚本。

于 2012-11-01T14:48:55.487 回答