Monday, December 24, 2012

Finding foriegn key table names which primary key is using in other tables


Finding table names in which a primary key of any table is used as foriegn key.
SELECT
    ConstraintName = fk.name,
    TableName = t.name,
    ColumnName = c.nameFROM
    sys.foreign_keys fkINNER JOIN 
    sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.OBJECT_IDINNER JOIN 
    sys.tables t ON fk.parent_object_id = t.OBJECT_IDINNER JOIN 
    sys.columns c ON fkc.parent_object_id = c.OBJECT_ID AND fkc.parent_column_id = c.column_idINNER JOIN 
    sys.tables tref ON fk.referenced_object_id = tref.OBJECT_IDINNER JOIN 
    sys.columns cref ON fkc.referenced_object_id = cref.OBJECT_ID AND fkc.referenced_column_id = cref.column_idWHERE
    tref.Name = 'tCurrencyCode'
    AND cref.Name = 'CurrencyId'

Enjoy.

No comments:

Post a Comment