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.
  1. select * from sysobjects where type='f'
Output

Method 2

Using this query, we can find all the foreign keys in a selected table.
  1. EXEC sp_fkeys 'Catalog'
Output

Method 3

Using this query, we can find all the foreign keys in a current database with more information.
  1. SELECT RC.CONSTRAINT_NAME FK_Name
  2. , KF.TABLE_SCHEMA FK_Schema
  3. , KF.TABLE_NAME FK_Table
  4. , KF.COLUMN_NAME FK_Column
  5. , RC.UNIQUE_CONSTRAINT_NAME PK_Name
  6. , KP.TABLE_SCHEMA PK_Schema
  7. , KP.TABLE_NAME PK_Table
  8. , KP.COLUMN_NAME PK_Column
  9. , RC.MATCH_OPTION MatchOption
  10. , RC.UPDATE_RULE UpdateRule
  11. , RC.DELETE_RULE DeleteRule
  12. FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
  13. JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF ON RC.CONSTRAINT_NAME = KF.CONSTRAINT_NAME
  14. JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME
Output

Hope this is helpful.