Skip to content

Instantly share code, notes, and snippets.

@gourab5139014
Last active March 26, 2024 14:59
Show Gist options
  • Save gourab5139014/791224 to your computer and use it in GitHub Desktop.
Save gourab5139014/791224 to your computer and use it in GitHub Desktop.
SQL Server Script to show all FK relationships in the current database
SELECT
fk.name 'FK Name',
tp.name 'Parent table',
cp.name, cp.column_id,
tr.name 'Referenced table',
cr.name, cr.column_id
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
tp.name, cp.column_id
@beagley
Copy link

beagley commented Sep 23, 2021

Just what I needed. Thx!! (small typo 'Refrenced')

@FranzM91
Copy link

FranzM91 commented Sep 9, 2022

just what I was looking for!!! thank you so much for sharing!!!!

@hiltonjrlucas
Copy link

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment