SELECT DISTINCT schema_name(fk_tab.schema_id) + '.' + fk_tab.name as foreign_table, '>-' as rel, schema_name(pk_tab.schema_id) + '.' + pk_tab.name as primary_table FROM sys.foreign_keys fk INNER JOIN sys.tables fk_tab on fk_tab.object_id = fk.parent_object_id INNER JOIN sys.tables pk_tab on pk_tab.object_id = fk.referenced_object_id WHERE pk_tab.[name] = 'Your table' -- enter table name here -- and schema_name(pk_tab.schema_id) = 'Your table schema name' ORDER BY schema_name(fk_tab.schema_id) + '.' + fk_tab.name, schema_name(pk_tab.schema_id) + '.' + pk_tab.name
Columns
- foreign_table – foreign tables schemas and names – the table you are looking for
- foreign_table – relationship symbol implicating FK and direction
- primary_table – primary (referenced) tables names with schema name – the table you provided as a parameter
Rows
- One row represents one referencing table
- Scope of rows: all tables referencing table with provided name (and optionally schema)
- Ordered by referencing table schema and name
Notes
- There can be more tables with the same name. If that’s the case, uncomment where clause and provide schema name
Sample results
All tables reference with FK Production.Product table in AdventureWorks database.
Thanks a lot to DataEdo.com for that amazing article.