我想整理一个sql查询,它将显示复合外键的哪些列对应于其主/唯一键的哪些列。
例如,如果数据库有
CREATE TABLE TA
(
B int,
C int
)
ALTER TABLE TA ADD CONSTRAINT [UK_CB] UNIQUE NONCLUSTERED
(
C ASC,
B ASC
)
CREATE TABLE TB
(
D int,
E int
)
ALTER TABLE TB ADD CONSTRAINT [FK_TA] FOREIGN KEY (D, E) REFERENCES TA(C, B)
然后我希望查询返回
| Pk/Uk | PK/UK Column | FK | FK Column |
--------------------------------------------
| UK_CB | C | FK_TA | D |
| UK_CB | B | FK_TA | E |
如果可能,我宁愿只使用INFORMATION_SCHEMA视图。
我知道INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE,但这只给了我特定约束中的列。
我可以加入INFORMATION_SCHEMA.COLUMNS并使用序数位置执行某些操作,但这会错误地假设关键引用符合序数。
有没有办法查询数据库以获得复合键之间的列对应关系?
答案 0 :(得分:0)
我在INFORMATION_SCHEMA视图中找不到经过验证的列顺序。但是,如果您可以使用系统目录视图(而不是INFORMATION_SCHEMA视图),则可以执行以下操作(这是sql fiddle)。我没有看到将它与pk / uk联系起来的直接方法,但你可以在pk / uk表上找到列:
SELECT
fk.name as constraint_name,
sfkc.constraint_column_id,
sfkc.parent_column_id,
fkt.name as fk_table,
fkc.name as fk_column,
sfkc.referenced_column_id,
pkt.name as pk_table,
pkc.name as pk_column
FROM sys.foreign_keys AS fk
JOIN sys.foreign_key_columns AS sfkc
ON fk.object_id = sfkc.constraint_object_id
JOIN sys.tables AS fkt
ON sfkc.parent_object_id = fkt.object_id
JOIN sys.columns as fkc
ON fkt.object_id = fkc.object_id
AND sfkc.parent_column_id = fkc.column_id
JOIN sys.tables AS pkt
ON sfkc.referenced_object_id = pkt.object_id
JOIN sys.columns as pkc
ON pkt.object_id = pkc.object_id
AND sfkc.referenced_column_id = pkc.column_id