2011-10-23 74 views

回答

1

它在裏面information_schema.table_constraints

編輯:

等待,我認爲information_schema.key_column_usage更好:

select * from information_schema.key_column_usage where table_name = '...' 

,然後如果你需要確保它確實是一個外鍵,使用你得到了約束名稱查詢TABLE_CONSTRAINTS從上面:

select * from information_schema.table_constraints where constraint_name = '...' 
+0

非常感謝,但我如何確定哪些列是與每列的關係。 –

+0

@niloo我編輯了我的答案,請再讀一遍 –

+0

Tjahono:非常感謝。 –

1

這將找到給定表上的所有FK約束。只需將'table_name'設置爲您的表格名稱即可。查詢如下:

DECLARE @TABLENAME VARCHAR(100); 
SET @TABLENAME='table_name'; 

SELECT 
    K_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 
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK 
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK 
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU 
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME 
INNER JOIN (
      SELECT 
       i1.TABLE_NAME, 
       i2.COLUMN_NAME 
      FROM 
       INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 
      INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 
       ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
      WHERE 
       i1.CONSTRAINT_TYPE = 'PRIMARY KEY' 
      ) PT 
    ON PT.TABLE_NAME = PK.TABLE_NAME 

    WHERE [email protected]