Query to Get the Forgien Key Name Their Primary Table and Referrence Table

Following Query will give you the List of Forgien Key in a Database with Their Primary and Referrence Tables Name.

Sample Query:
SELECT F.name AS ForgienKey,O2.name AS ParentTable,O3.name AS RefTable FROM sys.foreign_keys F
INNER JOIN Sys.Objects O2 ON O2.object_id=F.parent_object_id
INNER JOIN Sys.Objects O3 ON O3.object_id=F.referenced_object_id
If you want to get forgien key for a particular table then you can use like this:
SELECT F.name AS ForgienKey,O2.name AS ParentTable,O3.name AS RefTable FROM sys.foreign_keys F
INNER JOIN Sys.Objects O2 ON O2.object_id=F.parent_object_id
INNER JOIN Sys.Objects O3 ON O3.object_id=F.referenced_object_id
Where O3.name='Tbl_User'

0 comments: