首頁 > 資料庫 > mysql教程 > 如何使用'INFORMATION_SCHEMA”從 SQL Server 中的外鍵檢索引用的表和列資訊?

如何使用'INFORMATION_SCHEMA”從 SQL Server 中的外鍵檢索引用的表和列資訊?

DDD
發布: 2024-12-31 20:36:10
原創
447 人瀏覽過

How to Retrieve Referenced Table and Column Information from Foreign Keys in SQL Server using `INFORMATION_SCHEMA`?

使用Information_schema檢索外鍵引用

在SQL Server中,可以使用下列方式擷取與外鍵關聯的參考表和列名對information_schema 的查詢檢視。

查詢:

SELECT 
    KCU1.CONSTRAINT_SCHEMA AS FK_CONSTRAINT_SCHEMA, 
    KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME, 
    KCU1.TABLE_SCHEMA AS FK_TABLE_SCHEMA, 
    KCU1.TABLE_NAME AS FK_TABLE_NAME, 
    KCU1.COLUMN_NAME AS FK_COLUMN_NAME, 
    KCU1.ORDINAL_POSITION AS FK_ORDINAL_POSITION, 
    KCU2.CONSTRAINT_SCHEMA AS REFERENCED_CONSTRAINT_SCHEMA, 
    KCU2.CONSTRAINT_NAME AS REFERENCED_CONSTRAINT_NAME, 
    KCU2.TABLE_SCHEMA AS REFERENCED_TABLE_SCHEMA, 
    KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME, 
    KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME, 
    KCU2.ORDINAL_POSITION AS REFERENCED_ORDINAL_POSITION 
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC 

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 
    ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG  
    AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA 
    AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME 

INNER 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
登入後複製

此查詢檢索外鍵約束架構、名稱、表格架構、表格名稱、列名稱以及兩者的序號位置引用和被引用

範例:

要擷取表T_ALV_Ref_FilterDisplay 中外鍵 FA_MDT_ID 所引用的資料表和資料列,請使用下列查詢:

SELECT 
    FK_CONSTRAINT_SCHEMA,
    FK_CONSTRAINT_NAME,
    FK_TABLE_SCHEMA,
    FK_TABLE_NAME,
    FK_COLUMN_NAME,
    REFERENCED_TABLE_SCHEMA,
    REFERENCED_TABLE_NAME,
    REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1
    ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
    AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
    AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME

INNER 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.FK_TABLE_NAME = 'T_ALV_Ref_FilterDisplay'
    AND KCU1.FK_COLUMN_NAME = 'FA_MDT_ID';
登入後複製

結果將提供引用的資料表名稱(T_AP_Ref_Customer)和資料列名稱 (MDT_ID)。

以上是如何使用'INFORMATION_SCHEMA”從 SQL Server 中的外鍵檢索引用的表和列資訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板