all groups > sql server programming > september 2003 >
You're in the

sql server programming

group:

SQL to list all Child tables related to Parent


SQL to list all Child tables related to Parent penzina NO[at]SPAM iinet.net.au
9/10/2003 11:07:03 PM
sql server programming: SQL Server 2000

Can anyone help me with some T-SQL? If I have a parent table with
about 10 child tables (ie FK'd to parent). How can I construct a
SELECT clause which returns the name of these child tables, given the
name of the parent?

Thanks

Re: SQL to list all Child tables related to Parent Uri Dimant
9/11/2003 9:22:47 AM
Paul
SELECT P.id,C.id FROM Parent_Table P
INNER JOIN Child_Table C ON P.PK=C.FK

(PK -Primary Key,FK -Foreign Key)

[quoted text, click to view]

Re: SQL to list all Child tables related to Parent Jacco Schalkwijk
9/11/2003 9:41:53 AM
Hi Paul,

The following code uses the information_schema views, and for this to give
the correct results the foreign keys have to refererence the primary key or
a unique constraint on the parent table. It also possible (but bad practice)
to reference a unique index on the parent table, but then the code below
won't work.

SELECT f.table_name AS foreign_key_table, p.table_name AS primary_key_table
FROM information_schema.table_constraints f
INNER JOIN information_schema.referential_constraints r
ON f.constraint_name = r.constraint_name
INNER JOIN information_schema.table_constraints p
ON r.unique_constraint_name = p.constraint_name
WHERE p.table_name = '<your table>'


--
Jacco Schalkwijk MCDBA, MCSD, MCSE
Database Administrator
Eurostop Ltd.


[quoted text, click to view]

Re: SQL to list all Child tables related to Parent penzina NO[at]SPAM iinet.net.au
9/12/2003 10:24:48 PM
That's it. Thanks for your help Jacob

Cheers
Paul

[quoted text, click to view]
AddThis Social Bookmark Button