Lists all foreign keys (source and ref columns) in a MSSQL database

This script lists all foreign key references in a MSSQL database, using system tables:

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)


No comments: