List all FKeys in your Database (SQL Server)

TechGnome

Well-known member
Joined
May 23, 2005
Messages
896
Programming Experience
10+
The following query will list all of the Foreign Keys in your database. It returns the name of the FKey, the source table (where the FKey resides) the destination table (that has the PKey linked to) and the column in both tables involved. It also lists any CASCADE action (if any).

VB.NET:
Expand Collapse Copy
Select
Object_Name(constid) as ConstraintName,
Object_Name(fkeyid) as SourceTable,
(select column_name from information_schema.columns where table_name =
Object_Name(fkeyid) And Ordinal_Position = fkey) as SourceColumn,
Object_Name(rkeyid) as DestinationTable,
(select column_name from information_schema.columns where table_name =
Object_Name(rkeyid) And Ordinal_Position = rkey) as DestinationColumn,
(select Update_Rule from Information_Schema.Referential_Constraints
Where Constraint_Name = Object_Name(constid)) as UpdateRule,
(select Delete_Rule from Information_Schema.Referential_Constraints
Where Constraint_Name = Object_Name(constid)) as DeleteRule
from sysforeignkeys

If you want to limit the results from a table or tow, add this where clause:
VB.NET:
Expand Collapse Copy
WHERE Object_Name(rkeyid) IN ('tableOne', 'TableTwo')
Just include the list of tables you want FKeys from.

This code is provided as is, and with no warranty, implied or not.

-tg
 
Back
Top