Skip to content

Instantly share code, notes, and snippets.

@szunyog
Created November 21, 2013 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szunyog/7579122 to your computer and use it in GitHub Desktop.
Save szunyog/7579122 to your computer and use it in GitHub Desktop.
Lists all foreign keys (source and ref columns) in a MSSQL database.
SELECT
t.name AS TableWithForeignKey,
c.name AS ForeignKeyColumn,
r.name AS ReferencedTable,
rc.name AS ReferencedColumnName
FROM sys.foreign_key_columns AS fk
inner join sys.tables AS t ON fk.parent_object_id = t.object_id
inner join sys.columns AS c ON (t.object_id = c.object_id AND fk.parent_column_id = c.column_id)
inner join sys.tables AS r ON fk.referenced_object_id = r.object_id
inner join sys.columns AS rc ON (r.object_id = rc.object_id AND rc.column_id = fk.referenced_column_id)
ORDER BY
TableWithForeignKey,
fk.constraint_column_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment