查询知道一个表被引用了多少个其他表

时间:2017-06-10 03:18:00

标签: sql-server sql-server-2008

我最近开始使用Microsoft SQL Server,并且有一个以下查询从名为tblPole的表中获取数据,请求您提供查询,通过该查询我可以知道此表被引用到多少其他表中下面的数据库是我的查询

SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id

对于所有表格,以下数据表中的关系是我正在使用的查询

{{1}}

1 个答案:

答案 0 :(得分:0)

使用此查询:

SELECT  obj.name AS FK_NAME,
        sch.name AS [schema_name],
        tab1.name AS [table],
        col1.name AS [column],
        tab2.name AS [referenced_table],
        col2.name AS [referenced_column]
    FROM sys.foreign_key_columns fkc
    INNER JOIN sys.objects obj
        ON obj.object_id = fkc.constraint_object_id
    INNER JOIN sys.tables tab1
        ON tab1.object_id = fkc.parent_object_id
    INNER JOIN sys.schemas sch
        ON tab1.schema_id = sch.schema_id
    INNER JOIN sys.columns col1
        ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
    INNER JOIN sys.tables tab2
        ON tab2.object_id = fkc.referenced_object_id
    INNER JOIN sys.columns col2
        ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
    where  tab1.name = 'tblPole'