Know relationships between all the tables of database in SQL Server Know relationships between all the tables of database in SQL Server database database

Know relationships between all the tables of database in SQL Server


Sometimes, a textual representation might also help; with this query on the system catalog views, you can get a list of all FK relationships and how the link two tables (and what columns they operate on).

SELECT    fk.name 'FK Name',    tp.name 'Parent table',    cp.name, cp.column_id,    tr.name 'Refrenced table',    cr.name, cr.column_idFROM     sys.foreign_keys fkINNER JOIN     sys.tables tp ON fk.parent_object_id = tp.object_idINNER JOIN     sys.tables tr ON fk.referenced_object_id = tr.object_idINNER JOIN     sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_idINNER JOIN     sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_idINNER JOIN     sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_idORDER BY    tp.name, cp.column_id

Dump this into Excel, and you can slice and dice - based on the parent table, the referenced table or anything else.

I find visual guides helpful - but sometimes, textual documentation is just as good (or even better) - just my 2 cents.....


Just another way to retrieve the same data using INFORMATION_SCHEMA

The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.

sqlauthority way

SELECTK_Table = FK.TABLE_NAME,FK_Column = CU.COLUMN_NAME,PK_Table = PK.TABLE_NAME,PK_Column = PT.COLUMN_NAME,Constraint_Name = C.CONSTRAINT_NAMEFROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS CINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAMEINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAMEINNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAMEINNER JOIN (SELECT i1.TABLE_NAME, i2.COLUMN_NAMEFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAMEWHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY') PT ON PT.TABLE_NAME = PK.TABLE_NAME---- optional:ORDER BY1,2,3,4WHERE PK.TABLE_NAME='something'WHERE FK.TABLE_NAME='something'WHERE PK.TABLE_NAME IN ('one_thing', 'another')WHERE FK.TABLE_NAME IN ('one_thing', 'another')