Is it possible to find foreign key relationships with a SQL query?
The database is external to me and I am unable to access it directly to see the links through Server Management Studio.
To retrieve a list of Foreign keys, you can run this query:
SELECT t.name AS FKTableName
, fk.name AS NameOfForeignKey
, pc.name AS FKColumn
, rt.name AS ReferencedTable
, c.name AS ReferencedColumn
FROM sys.foreign_key_columns AS fkc
INNER JOIN sys.foreign_keys AS fk ON fkc.constraint_object_id = fk.object_id
INNER JOIN sys.tables AS t ON fkc.parent_object_id = t.object_id
INNER JOIN sys.tables AS rt ON fkc.referenced_object_id = rt.object_id
INNER JOIN sys.columns AS pc ON fkc.parent_object_id = pc.object_id
AND fkc.parent_column_id = pc.column_id
INNER JOIN sys.columns AS c ON fkc.referenced_object_id = c.object_id
AND fkc.referenced_column_id = c.column_id
This query can also be made more complex if you require additional information for your setup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With