sys.foreign_key_columns (Transact-SQL)

適用於:Microsoft Fabric 中的 SQL ServerAzure SQL 資料庫 Azure SQL 受控執行個體 Azure Synapse Analytics AnalyticsPlatform System (PDW)Warehouse

針對組成外鍵的每個數據行或一組數據行,各包含一個數據列。

資料行名稱 資料類型 描述
constraint_object_id int FOREIGN KEY 條件約束的標識碼。
constraint_column_id int 組成FOREIGN KEY的數據行標識碼或數據行集合(1..n ,其中 n是資料行數目)。
parent_object_id int 條件約束之父系的標識碼,這是參考物件。
parent_column_id int 父數據行的標識碼,這是參考數據行。
referenced_object_id int 具有候選索引鍵之參考對象的標識碼。
referenced_column_id int 參考數據行的識別碼(候選索引鍵數據行)。

權限

目錄檢視中元數據的可見度僅限於用戶擁有的安全性實體,或用戶獲授與某些許可權的安全性實體。 如需相關資訊,請參閱 Metadata Visibility Configuration

範例查詢

下列 Transact-SQL 查詢會擷取資料庫中的所有外鍵,包括其相關的數據表和數據行。

SELECT fk.name AS ForeignKeyName
    , t_parent.name AS ParentTableName
    , c_parent.name AS ParentColumnName
    , t_child.name AS ReferencedTableName
    , c_child.name AS ReferencedColumnName
FROM sys.foreign_keys fk 
INNER JOIN sys.foreign_key_columns fkc
    ON fkc.constraint_object_id = fk.object_id
INNER JOIN sys.tables t_parent
    ON t_parent.object_id = fk.parent_object_id
INNER JOIN sys.columns c_parent
    ON fkc.parent_column_id = c_parent.column_id  
    AND c_parent.object_id = t_parent.object_id 
INNER JOIN sys.tables t_child
    ON t_child.object_id = fk.referenced_object_id
INNER JOIN sys.columns c_child
    ON c_child.object_id = t_child.object_id
    AND fkc.referenced_column_id = c_child.column_id
ORDER BY t_parent.name, c_parent.name;

另請參閱