简体   繁体   中英

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.

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.

I am aware of INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE, but that only gives me the columns in the particular constraint.

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.

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. 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 ). 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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