2014-03-12 64 views

回答

1

您可以從INFORMATION_SCHEMA表中獲取約束信息。以下腳本將爲您提供主鍵和外鍵以及表的列表。

WITH PrimaryTable 
      AS (
       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' 
      ) 
    SELECT PK.TABLE_NAME AS PK_Table 
      ,PT.COLUMN_NAME AS PK_Column 
      ,FK.TABLE_NAME AS FK_Table 
      ,CU.COLUMN_NAME AS FK_Column 
      ,C.CONSTRAINT_NAME AS 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 PrimaryTable AS PT 
      ON PT.TABLE_NAME = PK.TABLE_NAME 
相關問題