Sunday, February 26, 2012

find all tables that a table is related to

how can i find all the names of tables that a specific table is related to in tsql?

sp_depends

Displays information about database object dependencies (for example, the views and procedures that depend on a table or view, and the tables and views that are depended on by the view or procedure). References to objects outside the current database are not reported.

Examples

This example lists the database objects that depend on the Customers table.

USE Northwind

EXEC sp_depends 'Customers'

|||

Assuming you have referential integrity in place you can also query the sys.sysforeignkeys view in 2005 or the sysforeignkeys table in 2000. Here is a query returning all table associations (2005 syntax, to use in 2000 remove "sys." prefix):

SELECT

o.name [parentTable]

,o2.name [childTable]

FROM

sys.sysobjects o

INNER JOIN sys.sysforeignkeys fk ON fk.rkeyid = o.id

INNER JOIN sys.sysobjects o2 ON o2.id = fk.fkeyid AND o2.id <> o.id

WHERE

o.name = 'myTable'

No comments:

Post a Comment