SQL Query通过外键依赖获取表名

时间:2012-11-01 14:28:27

标签: sql sql-server tsql foreign-keys

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

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

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

select * from sys.tables st
join sys.foreign_keys sfk on st.object_id = sfk.parent_object_id 
where sfk.name = 'Foreign_Key'

答案 2 :(得分:-2)

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

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

从那里,构建可以根据需要执行的脚本。