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
 General SQL Server Forums
 New to SQL Server Programming
 Query for multi level dependencies

Author  Topic 

Ranjit.ileni
Posting Yak Master

183 Posts

Posted - 2011-09-13 : 04:18:04
Hi all,

create table #temp
(
ID int
,IntroducerID int
)

insert into #temp
select 1,1 union all
select 2,1 union all
select 3,2 union all
select 4,2 union all
select 5,3 union all
select 6,3 union all
select 7,4 union all
select 8,4 union all
select 9,5 union all
select 10,5


SELECT * FROM #TEMP

Query need To select internal dependencies (like tree structure)

Expected Output:
IF IntroducerID=3 then Output should be

ID IntroducerID
5 3
6 3
9 5
10 5

IF IntroducerID=2 then Output should be

ID IntroducerID
3 2
4 2
5 3
6 3
7 4
8 4
9 5
10 5


IF IntroducerID=1 then Output should be

ID IntroducerID
1 1
2 1
3 2
4 2
5 3
6 3
7 4
8 4
9 5
10 5


Please help me
--Ranjit

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-13 : 04:34:24
[code]
;with cte(ID, IntroducerID)
as
(
select ID, IntroducerID
from #temp
where IntroducerID=@IntroducerID
union all
select t.ID,t.IntroducerID
from cte c
join #temp t
on t.IntroducerID =c.ID
)
select * from cte
option (maxrecursion 0)
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Ranjit.ileni
Posting Yak Master

183 Posts

Posted - 2011-09-13 : 04:36:59
Thanks visakh16,

Recursive CTEs are really very hlepfull

--Ranjit
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-13 : 04:46:02
welcome
yeah...they really are

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -