In this blog, we are trying to find in how many ways, we can find a foreign key in SQL Server.
There are so many ways to find out but currently, I am going to talk about only 3 ways.
I am using ReportServer database for this demo.
Method 1
Using this query, we can find all the foreign keys in current database.
- select * from sysobjects where type='f'
Method 2
Using this query, we can find all the foreign keys in a selected table.
Using this query, we can find all the foreign keys in a selected table.
- EXEC sp_fkeys 'Catalog'
Output


Method 3
Using this query, we can find all the foreign keys in a current database with more information.
Using this query, we can find all the foreign keys in a current database with more information.
- SELECT RC.CONSTRAINT_NAME FK_Name
- , KF.TABLE_SCHEMA FK_Schema
- , KF.TABLE_NAME FK_Table
- , KF.COLUMN_NAME FK_Column
- , RC.UNIQUE_CONSTRAINT_NAME PK_Name
- , KP.TABLE_SCHEMA PK_Schema
- , KP.TABLE_NAME PK_Table
- , KP.COLUMN_NAME PK_Column
- , RC.MATCH_OPTION MatchOption
- , RC.UPDATE_RULE UpdateRule
- , RC.DELETE_RULE DeleteRule
- FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
- JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF ON RC.CONSTRAINT_NAME = KF.CONSTRAINT_NAME
- JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME

Hope this is helpful.

Hadshana KamalanathanPosted Jul 16, 2018, 10:42 AM
Thank you for sharing.
Sagar Pandurang KapPosted Dec 11, 2017, 1:07 AM
In my query its giving error as The request for procedure 'sysobjects' failed because 'sysobjects' is a view object.
Sagar Pandurang KapPosted Dec 11, 2017, 1:07 AM
What is sysobject in first query