Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 find the hierarchy

Author  Topic 

inbs
Aged Yak Warrior

860 Posts

Posted - 2010-07-11 : 10:31:54
i have this tableA

ChildId Name ParnetId
1 a -1
2 b -1
3 c 1
4 d 3
5 e 2


i want to get

ChildId ChildName ParnetID ParnetName GrandId GrandName
4 d 3 c 1 a
5 e 2 b

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2010-07-11 : 17:27:32
try this:

create table tableA
(childID int
,name char(1)
,parentID int
)

insert into tableA
select 1,'a',-1 union all
select 2,'b',-1 union all
select 3,'c',1 union all
select 4,'d',3 union all
select 5,'e',2


select
G1.childID as G1_childID
,G1.name as G1_childName
,G1.parentID as G2_parentID
,g2.name as G2_parentName
,G2.parentID as G3_grandParentID
,G3.name as G3_grandParendName
into tableB
From tableA as G1 --generation1
join tableA as G2 --generation2
on g1.parentID = g2.childID
join tableA as G3 --generation3
on g2.parentID = g3.childID
where
g1.parentID > 0

union all

select
G1.childID as G1_childID
,G1.name as G1_childName
,G1.parentID as G2_parentID
,g2.name as G2_parentName
,'' G3_grandParentID
,'' as G3_grandParendName

From tableA as G1 --generation1
join tableA as G2 --generation2
on g1.parentID = g2.childID
where
g1.parentID > 0

union all

select
G1.childID as G1_childID
,G1.name as G1_childName
,'' as G2_parentID
,'' as G2_parentName
,'' G3_grandParentID
,'' as G3_grandParendName

From tableA as G1 --generation1
where
g1.parentID > 0
--(7 row(s) affected)



select
x.*
into tableC
from (
select * from tableB
except
select * from tableB
where G3_grandParentID = G2_ParentID
or G2_ParentID = G1_ChildID
)x
where x.g3_grandparentID > 0


select * from tableC
union all

select * from
(
select * from tableB
except
select * from tableB
where G3_grandParentID = G2_ParentID
or G2_ParentID = G1_ChildID
) as x
where
x.G1_childID > (Select G1_childID from tablec)

Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2010-07-11 : 23:20:21
will the level more than 3 lvl?


Hope can help...but advise to wait pros with confirmation...
Go to Top of Page

inbs
Aged Yak Warrior

860 Posts

Posted - 2010-07-12 : 09:32:08
thanks slimt_slimt,i do something same
waterduck-yes it could be more than 3 level
Go to Top of Page

inbs
Aged Yak Warrior

860 Posts

Posted - 2010-07-14 : 12:11:29
how can i do it something generic.(when i gave 3 lvl or 4 or 5 )?
Go to Top of Page
   

- Advertisement -