You can use something like this:
SELECT
FKName = fk.name,
ParentTable = tpar.name,
ParentColumn = colpar.name,
ReferencedTable = tref.name,
ReferencedColumn = colref.name
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.tables tpar ON fk.parent_object_id = tpar.object_id
INNER JOIN
sys.columns colpar ON fkc.parent_object_id = colpar.object_id AND fkc.parent_column_id = colpar.column_id
INNER JOIN
sys.tables tref ON fk.referenced_object_id = tref.object_id
INNER JOIN
sys.columns colref ON fkc.referenced_object_id = colref.object_id AND fkc.referenced_column_id = colref.column_id
But of course, you can have multiple foreign keys between TableA
and TableB
, and they can go "both ways" - you can have on FK going from ParentTable = TableA
to ReferencedTable = TableB
and another going from ParentTable = TableB
to ReferencedTable = TableA
.
So to find all foreign keys between two tables, use something like this:
WHERE
(ParentTable = 'TableA' AND ReferencedTable = 'TableB') OR
(ParentTable = 'TableB' AND ReferencedTable = 'TableA')
And yes, if you want to - you can wrap this up in a function, if you'd like - I wouldn't recommend doing it, however.