2014-01-13 55 views
0

我已經寫了一個查詢來找出數據庫中表的列名。如何找出表的列依賴關係

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 

到目前爲止,我已經得到了預期的結果,但無論專欄中,我在找我要找出列相關的表的依賴。通過執行上面的查詢,我得到了表名和列名。

如何獲得列相關的從屬表?

+0

究竟是什麼的 '依賴性' 對你意味着什麼?你是否在數據庫或其他方面尋找定義良好的外鍵關係? – OzrenTkalcecKrznaric

+0

在查詢中,我給列名稱messageID.So我需要獲得消息ID列依賴表。在那裏我需要在MessageID列上取決於這些表。 – mohan111

回答

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 
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 
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