sys.foreign_key_columns (Transact-SQL)

适用于:SQL ServerAzure SQL 数据库Azure SQL 托管实例Azure Synapse AnalyticsAnalytics Platform System (PDW)Microsoft Fabric 中的仓库

组成外键的每一列或列集在表中对应一行。

列名称 数据类型 说明
constraint_object_id int FOREIGN KEY 约束的 ID。
constraint_column_id int 组成 FOREIGN KEY(1..n,其中 n 为列数)的列或列集的 ID。
parent_object_id int 作为引用对象的约束父级的 ID。
parent_column_id int 作为引用列的父列的 ID。
referenced_object_id int 具有候选键的引用对象的 ID。
referenced_column_id int 被引用列(候选键列)的 ID。

权限

目录视图中元数据的可见性仅限于用户拥有的安全对象,或者向用户授予了某些权限的安全对象。 有关详细信息,请参阅 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;

另请参阅