Friday, March 23, 2012

Related tables

Is it possible to retrieve all tables that a given one is related to
via foreign keys?Try this:

SELECT DISTINCT o1.name FROM sysreferences r
INNER JOIN sysobjects o1 ON o1.id=r.fkeyid
INNER JOIN sysobjects o2 ON o2.id=r.rkeyid
WHERE o2.name='YourTable'
/*
UNION
SELECT DISTINCT o2.name FROM sysreferences r
INNER JOIN sysobjects o1 ON o1.id=r.fkeyid
INNER JOIN sysobjects o2 ON o2.id=r.rkeyid
WHERE o1.name='YourTable'
*/

Razvan|||Razvan Socol wrote:
> Try this:
> SELECT DISTINCT o1.name FROM sysreferences r
> INNER JOIN sysobjects o1 ON o1.id=r.fkeyid
> INNER JOIN sysobjects o2 ON o2.id=r.rkeyid
> WHERE o2.name='YourTable'
> /*
> UNION
> SELECT DISTINCT o2.name FROM sysreferences r
> INNER JOIN sysobjects o1 ON o1.id=r.fkeyid
> INNER JOIN sysobjects o2 ON o2.id=r.rkeyid
> WHERE o1.name='YourTable'
> */

Thanks, this gets me closer to the goal. By the way, if I try it as it
is, it returns no rows at first. When I remove the WHERE clause, then
it works!

I will need to look more into the system tables.

No comments:

Post a Comment