简体   繁体   English

使用TSQL如何确定哪一个化合物外键的列对应于化合物主/唯一键的哪一列?

[英]Using tsql how to determine which column of a compound foreign key corresponds to which column of a compound primary/unique key?

I want to put together a sql query that will show me which columns of compound foreign keys correspond to which columns of their primary/unique key. 我想放一个sql查询,该查询将向我显示复合外键的哪些列对应于其主键/唯一键的哪些列。

For example, if the database had 例如,如果数据库具有

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)

Then I would want the query to return 然后我想查询返回

| Pk/Uk | PK/UK Column |  FK   | FK Column |
--------------------------------------------
| UK_CB |      C       | FK_TA |     D     |
| UK_CB |      B       | FK_TA |     E     |

If possible, I would prefer to use only INFORMATION_SCHEMA views. 如果可能,我宁愿仅使用INFORMATION_SCHEMA视图。

I am aware of INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE, but that only gives me the columns in the particular constraint. 我知道INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE,但这只为我提供了特定约束中的列。

I could join to INFORMATION_SCHEMA.COLUMNS and do something with ordinal position, but that makes the false assumption that key reference are in the ordinal order. 我可以加入INFORMATION_SCHEMA.COLUMNS并以顺序位置进行操作,但是这错误地假设关键引用是按顺序排列的。

Is there a way to query the database to get the column correspondence between compound keys? 有没有一种查询数据库以获取复合键之间的列对应关系的方法?

I can't find a verified column order in the INFORMATION_SCHEMA views. 我在INFORMATION_SCHEMA视图中找不到经过验证的列顺序。 However, if you can use the system catalog views (instead of the INFORMATION_SCHEMA views) you could do the following (Here's a sql fiddle ). 但是,如果可以使用系统目录视图(而不是INFORMATION_SCHEMA视图),则可以执行以下操作(这是一个sql小提琴 )。 I don't see a direct way to relate it to the pk / uk, but you can find the columns on the pk/uk table: 我看不到将其与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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM