Skip to content

Instantly share code, notes, and snippets.

@niikoo
Created June 7, 2021 08:27
Show Gist options
  • Save niikoo/bcd6cce6e9195d6d8d48537417ca174c to your computer and use it in GitHub Desktop.
Save niikoo/bcd6cce6e9195d6d8d48537417ca174c to your computer and use it in GitHub Desktop.
SELECT
fk.name 'Foreign Key Name',
tp.name 'Parent table',
cp.name 'Parent colName',
cp.column_id 'Parent colId',
tr.name 'Refrenced table',
cr.name 'Referenced colName',
cr.column_id 'Referenced colId'
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment