SQL Server:如何从信息架构中检索外键引用
在 SQL Server 中,检索有关外键引用的信息对于了解数据关系并维护数据库完整性。通过利用信息模式,您可以访问有关外键的有价值的元数据,包括它们引用的表和列。
下面显示的 SQL 查询提供了从信息模式中提取外键引用的全面解决方案:
`选择
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
内部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`
在此查询中:
通过使用此查询,您可以获得 SQL Server 数据库内外键关系的全面视图,使您能够执行数据验证、更新传播以及与数据管理相关的其他重要任务.
以上是如何使用信息架构检索 SQL Server 中的外键引用?的详细内容。更多信息请关注PHP中文网其他相关文章!