2
查找与给定主键关联的外键
我想要一种通过PK / FK关系建立给定数据库中的哪些列的方法。我可以通过以下方式返回给定表的PK / FK信息 SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS cu WHERE EXISTS ( SELECT tc.* FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc WHERE tc.CONSTRAINT_CATALOG = 'MyDatabase' AND tc.TABLE_NAME = 'MyTable' /*AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'*/ AND tc.CONSTRAINT_NAME = cu.CONSTRAINT_NAME); GO 但是对于从这样的查询返回的PK,我如何建立关联的FK(假设有一个)? 我知道您也可以通过以下方式获取引用的表: SELECT CONSTRAINT_NAME = name, FOREIGN_SCHEMA = OBJECT_SCHEMA_NAME(parent_object_id), FOREIGN_TABLE = OBJECT_NAME(parent_object_id), …