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 2000 Forums
 SQL Server Development (2000)
 Iterative Query

Author  Topic 

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2004-12-08 : 08:37:15
I have a table called relations having these records

Id Description Pid
1 x 0
2 z 0
3 a 2
4 b 2
5 c 1
6 n 1
7 p 4
8 r 3
9 s 2
10 t 6

I want to write a query to get all the relations
eg t's Pid is 6 which is id for n who has pid 1 which id for x
So the relation for t is t-n-x
similarly p has p-b-z

I used the following query





select * from(
Select R1.Description as "D5", "" as "D6" ,
"" as "D7" from Relations R1 where R1.Pid=0
union Select R1.Description as "D5", R2.Description as "D6" ,
"" as "D7" from Relations R1, Relations R2 where R1.Pid=R2.id and R2.Pid=0
union Select r1.D3,t1.d1 , t1.D2 from(
Select R1.Description as "D1", R2.Description as "D2" from Relations R1, Relations R2 where R1.Pid=R2.id) as t1,
(Select R1.Description as "D3", R2.Description as "D4" from Relations R1, Relations R2 where R1.Pid=R2.id ) r1
where r1.d4=t1.d1 ) t order by len(d7) asc, len(d6) asc,d5




which produced

D5 D6 D7
x
z
a z
b z
c x
n x
s z
p b z
r a z
t n x


But its working for maximum of three relations
How can I modify this query so that it will return the relations for any level

Thanks in advance

Madhivanan

Seventhnight
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2004-12-08 : 09:03:58
I'd say try reading through http://www.seventhnight.com/treestructs.asp,
but it seems to be down right now...

There is also: http://www.nigelrivett.net/RetrieveTreeHierarchy.html

and also: http://www.sqlteam.com/item.asp?ItemID=8866

EDIT: http://www.seventhnight.com/treestructs.asp should be back up in a few hours (sorry )

Corey
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2004-12-09 : 00:24:21

Thank you for giving useful links

Madhivanan
Go to Top of Page
   

- Advertisement -