从 SQL Server 中的 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 ,KCU2.TABLE_SCHEMA AS REFERENCED_TABLE_SCHEMA ,KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME ,KCU2.COLUMN_NAME AS 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
注意: Information_schema 不包含索引。要基于唯一索引查找外键,请参阅 SQL Server 的专有表。
外键引用检索示例:
考虑以下表结构:
CREATE TABLE [dbo].[T_ALV_Ref_FilterDisplay] ( [FA_MDT_ID] [varchar](20) NOT NULL, [FA_NAME] [varchar](255) NOT NULL ) CREATE TABLE [dbo].[T_AP_Ref_Customer] ( [MDT_ID] [varchar](20) NOT NULL, [CUST_NAME] [varchar](255) NOT NULL ) ALTER TABLE [dbo].[T_ALV_Ref_FilterDisplay] WITH CHECK ADD CONSTRAINT [FK_T_ALV_Ref_FilterDisplay_T_AP_Ref_Customer] FOREIGN KEY([FA_MDT_ID]) REFERENCES [dbo].[T_AP_Ref_Customer] ([MDT_ID])
要检索外键 [FA_MDT_ID] 引用的表和列,请执行以下命令查询:
SELECT FK_TABLE_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE FK_TABLE_NAME = 'T_ALV_Ref_FilterDisplay' AND FK_COLUMN_NAME = 'FA_MDT_ID'
结果会显示:
FK_TABLE_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME ---------------|----------------------|------------------------- T_ALV_Ref_FilterDisplay | T_AP_Ref_Customer | MDT_ID
这表明[T_ALV_Ref_FilterDisplay]中的外键[FA_MDT_ID]引用了[T_AP_Ref_Customer]中的[MDT_ID]列表。
以上是如何使用 SQL Server 的 INFORMATION_SCHEMA 检索外键引用?的详细内容。更多信息请关注PHP中文网其他相关文章!