I would like to use 2 queries, one that lists all the foreign keys for a given table with the following information Schema name, foreign table name and the other that lists all the primary keys.
Is this query that lists the primary keys correct:
select syssc.name as schemaname , cast(c.name as varchar(255)) as foreign_table ,
cast(p.name as varchar(255)) as primary_table
from sysobjects f
inner join sysobjects c on f.parent_obj = c.id
inner join sysreferences r on f.id = r.constid
inner join sysobjects p on r.rkeyid = p.id
inner join syscolumns rc on r.rkeyid = rc.id and r.rkey1 = rc.colid
inner join syscolumns fc on r.fkeyid = fc.id and r.fkey1 = fc.colid
left join syscolumns rc2 on r.rkeyid = rc2.id and r.rkey2 = rc.colid
left join syscolumns fc2 on r.fkeyid = fc2.id and r.fkey2 = fc.colid
inner join sys.tables syst on rc.id=syst.object_id
inner join sys.schemas syssc on syst.schema_id=syssc.schema_id
where f.type = 'F' AND c.name in ('table name' )
This is the query that i use now to get the foreign keys
select syssc.name as schemaname ,cast(c.name as varchar(255)) as foreign_table ,
cast(p.name as varchar(255)) as primary_table
from sysobjects f
inner join sysobjects c on f.parent_obj = c.id
inner join sysreferences r on f.id = r.constid
inner join sysobjects p on r.rkeyid = p.id
inner join syscolumns rc on r.rkeyid = rc.id and r.rkey1 = rc.colid
inner join syscolumns fc on r.fkeyid = fc.id and r.fkey1 = fc.colid
left join syscolumns rc2 on r.rkeyid = rc2.id and r.rkey2 = rc.colid
left join syscolumns fc2 on r.fkeyid = fc2.id and r.fkey2 = fc.colid
inner join sys.tables syst on rc.id=syst.object_id
inner join sys.schemas syssc on syst.schema_id=syssc.schema_id
where f.type = 'F' and p.name in ('table name')
Kindly check whether these queries are the right ones and the efficient ones.

table namethat are referenced by foreign keys in other tables, or the columns intable namethat reference other tables? – Aaron Bertrand Sep 12 '11 at 14:33