Find Foreign Keys

,

This script lists the name of the foreign key, table name, column name, referenced table name and referenced column name.

;With CTE As 
(Select    Object_Name(constraint_object_id) Constraint_Name, 
        Object_Name(parent_object_id) Table_Name,
        C.name Column_Name
From sys.foreign_key_columns FK
        Inner Join sys.columns C 
            On FK.parent_object_id = C.object_id
            And FK.parent_column_id = C.column_id)
Select    C.Constraint_Name,
        C.Table_Name,
        C.Column_Name, 
        Object_Name(FK.referenced_object_id) Referenced_Table_Name,
        SC.name Referenced_Column_Name
from CTE C
    Inner Join sys.foreign_key_columns FK 
        On C.Constraint_Name = Object_Name(FK.constraint_object_id)
    Inner Join sys.columns SC 
        On FK.referenced_object_id = SC.object_id
    And FK.referenced_column_id = SC.column_id

Rate

4.75 (8)

Share

Share

Rate

4.75 (8)