Last active
March 22, 2022 19:11
-
-
Save rruntsch/df1f428846f9e4c989936598c2a0df6d to your computer and use it in GitHub Desktop.
Get the foreign key relationships between SQL Server database tables.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- File Name: get_fk_relationships.sql | |
-- Description: Get the foreign key relationships between tables. | |
USE AdventureWorks2019; | |
GO | |
SELECT | |
fk.name AS [Foreign Key Name], | |
tp.name AS [Parent Table], | |
cp.name AS [Parent Table Column], | |
tr.name AS [Referenced Table], | |
cr.name AS [Referenced Table Column Name] | |
FROM sys.foreign_keys fk | |
INNER JOIN sys.tables tp | |
ON fk.parent_object_id = tp.object_id | |
INNER JOIN sys.tables tr | |
ON fk.referenced_object_id = tr.object_id | |
INNER JOIN sys.foreign_key_columns fkc | |
ON fkc.constraint_object_id = fk.object_id | |
INNER JOIN sys.columns cp | |
ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id | |
INNER JOIN sys.columns cr | |
ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id | |
ORDER BY [Parent Table], [Parent Table Column]; | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment