首页 > 数据库 > mysql教程 > 如何使用'INFORMATION_SCHEMA”从 SQL Server 中的外键检索引用的表和列信息?

如何使用'INFORMATION_SCHEMA”从 SQL Server 中的外键检索引用的表和列信息?

DDD
发布: 2024-12-31 20:36:10
原创
453 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板