I have following table structure:
create table Test(
ParentId int,
ChildId int
)
insert into Test(ParentId, ChildId)
select 1, NULL
union
select 1, 2
union
select 1, 3
union
select 2, NULL
union
select 2, 5
union
select 5, 6
union
select 6, 5
union
select 6, 8
I'm trying to build a result set of all parent child DIRECT and INDIRECT relationships. So suppose I pass the parameter of ParentID = 2, I would like the result set to return exactly as below:
ParentId ChildId
-------------------
2 NULL
2 5
5 6
6 8
1 2
So basically this shows all possible links that can be found in one table for Parent ID = 2. Starting off with Parent itself, it has Child Id which then has other relations with Child Id 6. Also the parent Id 2 falls under parent id 1 which should also show up in result set. Please note the relationship could expand to N number of levels. I hope you understand what I am trying to achieve here, if not then please let me know so that I can explain more clearly.
So far I have come up with below recursive query but it throws an error which is stated below:
DECLARE @ID INT = 2
;WITH MyCTE
AS (
SELECT ParentId
,ChildId
FROM Test
WHERE ParentId = @ID
UNION ALL
SELECT T.ParentId
,Test.ChildId
FROM Test
INNER JOIN MyCTE T ON Test.ParentID = T.ChildId
WHERE Test.ParentID IS NOT NULL
)
SELECT *
FROM MyCTE
Error:
The statement terminated. The maximum recursion 100 has been exhausted before statement completion
I have put up the code on SQLFiddle here for you guys to test and try.
I would really appreciate anyone who guides and helps me in achieving my desired result.