Technical Article

Get all the Child Tables up to N level

,

Get all the dependent tables for a master table  up to N level(Till the leaf ) you can either find dependency or you can find all the child tables.
To find the  Complete Relation
SELECT TableRelation
FROM   cte
Order by TableRelation
or 
To find only the Dependent Table only
SELECT DISTINCT DependentTable
FROM   cte
DECLARE @TableName AS VARCHAR(250)='<Table Name>'
;WITH cte AS 
(
SELECT cast(OBJECT_NAME (fkc.parent_object_id) as VARCHAR(MAX)) AS TableRelation, OBJECT_NAME(fkc.parent_object_id) AS DependentTable, fkc.parent_object_id AS 
       childID, 1 AS ReLevel
FROM   sys.foreign_key_columns fkc
WHERE  fkc.referenced_object_id = OBJECT_ID (@TableName)
UNION ALL
SELECT cast(c.TableRelation +'-->'+ OBJECT_NAME (fkc.parent_object_id) AS VARCHAR(MAX)) AS TableRelation, OBJECT_NAME(fkc.parent_object_id) AS DependentTable, fkc.parent_object_id AS 
       childID, c.ReLevel + 1
FROM   sys.foreign_key_columns fkc
       INNER JOIN cte c
            ON  fkc.referenced_object_id = c.Childid AND fkc.parent_object_id<>c.childid
)
SELECT TableRelation,DependentTable
FROM   cte

Rate

4.83 (6)

You rated this post out of 5. Change rating

Share

Share

Rate

4.83 (6)

You rated this post out of 5. Change rating