Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

Building Parent-Child Table Tree information Expand / Collapse
Author
Message
Posted Wednesday, July 9, 2008 10:37 PM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Thursday, January 23, 2014 7:34 AM
Points: 334, Visits: 75
Comments posted to this topic are about the item Building Parent-Child Table Tree information


Post #531348
Posted Thursday, July 10, 2008 2:29 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Monday, November 10, 2014 11:15 PM
Points: 24, Visits: 289
Nice code that may come in handy, esp for writing code to do cascading deletes. Expected a hierarchial tree of dependencies to be display in Management studio, something MS may consider for the future to make the life of DBA's easier.
Post #531431
Posted Thursday, July 10, 2008 2:41 AM


SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: Thursday, November 27, 2014 1:56 AM
Points: 998, Visits: 6,478
Ain't saying nothing until Joe Celko says it's OK :D

j/k, good article :)


-------------------------------------------------------------
"It takes 15 minutes to learn the game and a lifetime to master"
"Share your knowledge. It's a way to achieve immortality."


Post #531436
Posted Thursday, July 10, 2008 3:59 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Saturday, November 29, 2014 3:55 PM
Points: 3,244, Visits: 5,010
Nice Code.

I did the same thing with this query...


select ccu.table_schema + '.' + ccu.table_name as MTablename, ccu.column_name as Mcolname,
ccu1.table_schema + '.' + ccu1.table_name as Tablename, ccu1.column_name as colname
,ccu3.table_schema + '.' + ccu3.table_name as C2Tablename, ccu3.column_name as C2colname
,ccu5.table_schema + '.' + ccu5.table_name as C3Tablename, ccu5.column_name as C3colname
,ccu7.table_schema + '.' + ccu7.table_name as C4Tablename, ccu7.column_name as C4colname
,ccu9.table_schema + '.' + ccu9.table_name as C5Tablename, ccu9.column_name as C5colname
,ccu11.table_schema + '.' + ccu11.table_name as C6Tablename, ccu11.column_name as C6colname
from information_schema.constraint_column_usage CCU
inner join information_schema.referential_constraints RC on CCU.constraint_name=RC.unique_constraint_name
inner join information_schema.constraint_column_usage CCU1 on RC.constraint_name=ccu1.constraint_name
Left Outer join information_schema.constraint_column_usage CCU2 on CCU2.Table_Schema + '.' + CCU2.table_name = CCU1.Table_Schema + '.' + CCU1.table_name
Left Outer Join information_schema.referential_constraints RC2 on CCU2.constraint_name=RC2.unique_constraint_name
Left Outer Join information_schema.constraint_column_usage CCU3 on RC2.constraint_name=ccu3.constraint_name
Left Outer join information_schema.constraint_column_usage CCU4 on CCU4.Table_Schema + '.' + CCU4.table_name = CCU3.Table_Schema + '.' + CCU3.table_name
Left Outer Join information_schema.referential_constraints RC3 on CCU4.constraint_name=RC3.unique_constraint_name
Left Outer Join information_schema.constraint_column_usage CCU5 on RC3.constraint_name=ccu5.constraint_name
Left Outer join information_schema.constraint_column_usage CCU6 on CCU6.Table_Schema + '.' + CCU6.table_name = CCU5.Table_Schema + '.' + CCU5.table_name
Left Outer Join information_schema.referential_constraints RC4 on CCU6.constraint_name=RC4.unique_constraint_name
Left Outer Join information_schema.constraint_column_usage CCU7 on RC4.constraint_name=ccu7.constraint_name
Left Outer join information_schema.constraint_column_usage CCU8 on CCU8.Table_Schema + '.' + CCU8.table_name = CCU7.Table_Schema + '.' + CCU7.table_name
Left Outer Join information_schema.referential_constraints RC5 on CCU8.constraint_name=RC5.unique_constraint_name
Left Outer Join information_schema.constraint_column_usage CCU9 on RC5.constraint_name=ccu9.constraint_name
Left Outer join information_schema.constraint_column_usage CCU10 on CCU10.Table_Schema + '.' + CCU10.table_name = CCU9.Table_Schema + '.' + CCU9.table_name
Left Outer Join information_schema.referential_constraints RC6 on CCU10.constraint_name=RC6.unique_constraint_name
Left Outer Join information_schema.constraint_column_usage CCU11 on RC6.constraint_name=ccu11.constraint_name
where ccu.constraint_name not in (select constraint_name from information_schema.referential_constraints)
and ccu.table_schema + '.' + ccu.table_name in ('dbo.Portal_users')




The thing which makes the difference is that I have to add the joins manually if I have to add the level to which i need to go to find the childs. Your code is generic in this case.

I was just thinking to go into string processing to resolve this issue in my code, but thanks to you, now I will be using your code for my future developments.

Thanks once again and NICE CODE...

Atif Sheikh


----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Sometimes, winning is not an issue but trying.

You can check my BLOG here

Post #531462
Posted Thursday, July 10, 2008 7:34 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Wednesday, March 6, 2013 8:22 AM
Points: 12, Visits: 120
Great stuff. Thanks for doing this.
Post #531589
Posted Thursday, July 10, 2008 8:00 AM


SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Thursday, July 10, 2014 1:33 PM
Points: 457, Visits: 476
Terrific code! I really like it! However it is dependent on a starting table name in which the tree only goes down. What about the parents of the starting table? Could it be written to go both ways to pick up a Person table as being the parent of the SalesPerson and possibly however many parents of Person there might be?

Ron K.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." -- Martin Fowler
Post #531628
Posted Thursday, July 10, 2008 8:18 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Friday, September 26, 2014 2:59 PM
Points: 4, Visits: 161
I was working on views or codes to get the same information. Thank you for the codes - saved me a lot of time. Nice code, too!
Post #531653
Posted Thursday, July 10, 2008 12:09 PM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Friday, December 5, 2014 10:31 AM
Points: 13,872, Visits: 9,599
You can still end up with an infinite loop with this (well, it will loop till it hits the recursion limit).

Table1 has an FK that references Table3
Table2 has an FK that references Table1
Table3 has an FK that references Table2

So long as at least one of these keys doesn't have a Not Null constraint on the column, this data structure is possible. It's most likely to happen in many-to-many-to-many relations.

What you're better off doing, if this kind of chain-key relationship is possible in your database, is a self-referent outer-join in the recursive portion of the CTE, with an Is Null in the Where clause, including the Level column in part of the join.


- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread

"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
Post #531859
Posted Thursday, July 10, 2008 12:16 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Sunday, July 13, 2008 8:06 AM
Points: 2, Visits: 8
Try this. It takes this idea a step further and creates an entire select query based on the base table you provide.
Right now if you run it against Northwind it will create the following query for you:
/*
SELECT * FROM
[Employees] WITH (NOLOCK)
LEFT JOIN [EmployeeTerritories] WITH (NOLOCK) ON [EmployeeTerritories].EmployeeID=Employees.EmployeeID
INNER JOIN [Orders] WITH (NOLOCK) ON [Orders].EmployeeID=Employees.EmployeeID
LEFT join [Order Details] WITH (NOLOCK) ON [Order Details].OrderID=Orders.OrderID
*/
/*
Script Name: Recursive Table Layout
Author: Sean McDaniel
Purpose: Will start with table and work it's way back through the foreign keys pointing to it and so forth until it reaches the highest parent
Will also determine whether a left join or right join should be used based on whether the child table allows nulls in the column or not
*/
set nocount on
DECLARE @TableName varchar(200), @level int
/*
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
PUT IN THE TABLE YOU'D LIKE TO START WITH
*/
set @TableName='Employees'

set @level=1
declare @ParentChildTableTree table

(ParentTable sysname null,ChildTable sysname null,[Level] int null,Indent varchar(max) null, JOIN_INFO varchar(max));

insert into @ParentChildTableTree select null, null, @level, null, 'SELECT * FROM
[' + @TableName + '] WITH (NOLOCK)'
set @level=@level+1
insert into @ParentChildTableTree
select distinct rkeyid,fkeyid,@level as [Level],
@TableName + '->' + convert(varchar(max),object_name(fkeyid)) as Indent
, case when b1.isnullable=1 then 'INNER' else 'LEFT' end + ' JOIN [' + b.name + '] WITH (NOLOCK) ON [' + b.name + '].' + b1.name + '=' + c.name + '.' + c1.name
from sysforeignkeys a
INNER JOIN sysobjects b ON a.fkeyid=b.id AND b.xtype='U'
INNER JOIN syscolumns b1 ON a.fkeyid=b1.id AND a.fkey=b1.colid
INNER JOIN sysobjects c ON a.rkeyid=c.id AND c.xtype='U'
INNER JOIN syscolumns c1 ON a.rkeyid=c1.id AND a.rkey=c1.colid
where rkeyid = object_id(@TableName)
and rkeyid <> fkeyid
while @@ROWCOUNT >0
begin
set @level=@level+1
insert into @ParentChildTableTree
select distinct rkeyid,fkeyid,@level as [Level],
Indent + convert(varchar(max),object_name(fkeyid)) as Indent
, case when b1.isnullable=1 then 'INNER' else 'LEFT' end + ' join [' + b.name + '] WITH (NOLOCK) ON [' + b.name + '].' + b1.name + '=' + c.name + '.' + c1.name
from sysforeignkeys fk
INNER JOIN sysobjects b ON fk.fkeyid=b.id AND b.xtype='U'
INNER JOIN syscolumns b1 ON fk.fkeyid=b1.id AND fk.fkey=b1.colid
INNER JOIN sysobjects c ON fk.rkeyid=c.id AND c.xtype='U'
INNER JOIN syscolumns c1 ON fk.rkeyid=c1.id AND fk.rkey=c1.colid
join @ParentChildTableTree pc on fk.rkeyid=ChildTable
where rkeyid <> fkeyid
and pc.Level = @level -1
and not exists (select * from @ParentChildTableTree b where fk.rkeyid=b.ParentTable and fk.fkeyid=b.ChildTable)
end
select --object_name(ParentTable), Object_Name(ChildTable), Level, Indent,
space((Level-1) * 10) + JOIN_INFO from @ParentChildTableTree order by Indent
Post #531865
Posted Thursday, July 10, 2008 12:29 PM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Thursday, November 20, 2014 3:44 AM
Points: 1,260, Visits: 3,424
Interesting ... lot of stuff here and very rich article
thnx and no comment!



============================================================
SELECT YOUR PROBLEM FROM SSC.com WHERE PROBLEM DESCRIPTION =
http://www.sqlservercentral.com/articles/Best+Practices/61537/
Post #531872
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse