如何找出表的列依赖项

时间:2014-01-13 07:58:49

标签: sql-server tsql

我编写了一个查询来查找数据库中表的列名。

SELECT 
  t.NAME AS TABLEName,
  SCHEMA_NAME(schema_id) + '.' + c.name AS ColumnName
FROM 
  sys.tables t
  INNER JOIN sys.columns c 
    ON c.object_id = t.object_id
WHERE OBJECT_NAME(c.object_id) LIKE '%Message%'
ORDER BY t.NAME

到目前为止,我已经得到了预期的结果,但无论我想要什么列,我都想找出列相关表的依赖关系。通过执行上面的查询,我得到表名和列名。

如何获取与列相关的从属表?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT KCU1.TABLE_CATALOG,
       KCU1.TABLE_SCHEMA,
       KCU1.TABLE_NAME,
       KCU1.COLUMN_NAME,
       KCU2.TABLE_NAME   AS REFERENCED_TABLE_NAME,
       KCU2.COLUMN_NAME  AS REFERENCED_COLUMN_NAME
FROM   INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1
       JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
            ON  KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
            AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
            AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
       JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2
            ON  KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
            AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
            AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
            AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
WHERE  KCU1.TABLE_NAME LIKE '%Message%'
ORDER BY
       KCU1.TABLE_NAME,
       KCU1.COLUMN_NAME

答案 1 :(得分:0)

这可能会有所帮助。但是,您需要稍微调整一下以满足您的特定需求:

SELECT OBJECT_NAME(referenced_major_id) AS ReferingObject, 
    (SELECT o.type_Desc FROM sys.objects o
        WHERE o.object_id = d.referenced_major_id) AS ReferingObjType,
CASE WHEN referenced_minor_id <> 0 THEN COL_NAME(referenced_major_id, referenced_minor_id)
        ELSE '' END AS RefColumnName,
OBJECT_NAME(object_ID) AS ReferencedObject,
(SELECT o.type_Desc FROM sys.objects o
        WHERE o.object_id = d.object_id) AS ReferedObjType 
fROM sys.sql_dependencies d 

答案 2 :(得分:0)

如果您要查找引用名称中包含令牌消息的表中列的所有表/列,您可以使用:

;WITH PT AS (
    SELECT 
        tc1.TABLE_NAME, 
        tc2.COLUMN_NAME
    FROM 
        INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc1
        JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE tc2 
            ON tc1.CONSTRAINT_NAME = tc2.CONSTRAINT_NAME
    WHERE tc1.CONSTRAINT_TYPE = 'PRIMARY KEY')
SELECT
    FK_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM 
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
    JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK 
        ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
    JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK 
        ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
    JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU 
        ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
    JOIN PT 
        ON PT.TABLE_NAME = PK.TABLE_NAME
WHERE PK.TABLE_NAME LIKE '%Message%'
ORDER BY
    FK.TABLE_NAME,
    CU.COLUMN_NAME,
    PK.TABLE_NAME,
    PT.COLUMN_NAME