Sunday, February 26, 2017

Find relations between the tables

when you join a new company first thing you need to know about the tables and its relationships .This query will help to know the relations of the all the tables .Just select the database and run this query.

Tips: Export the result in excel and filters out the columns it is easy to find relations.


SELECT Object_name(rkeyid)  Parent_Table, 
       Object_name(fkeyid)  Child_Table, 
       Object_name(constid) FKey_Name, 
       c1.NAME              FKey_Col, 
       c2.NAME              Ref_KeyCol 
FROM   sys.sysforeignkeys s 
       INNER JOIN sys.syscolumns c1 
               ON ( s.fkeyid = c1.id 
                    AND s.fkey = c1.colid ) 
       INNER JOIN syscolumns c2 
               ON ( s.rkeyid = c2.id 
                    AND s.rkey = c2.colid ) 
ORDER  BY parent_table, 
          child_table 

No comments:

Post a Comment