Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Lists all foreign keys (source and ref columns) in a MSSQL database.
SELECT AS TableWithForeignKey, AS ForeignKeyColumn, AS ReferencedTable, 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment