Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Recursive query with two parents

$
0
0
I am currently struggling with a query to recurse up/down a tree. In real life we have a junction table with two FKs pointing to the parent. Both Id and Parent Id are not nullable. Below is an example of what I am trying to depict without complicating it with the parent table.[code="sql"]('Book1',1,2),('Book1',1,3),('Book3',3,4),('Book4',4,5),('Book6',6,5),('Book7',7,6)--Book 2/5 are the top most nodesDECLARE @id as int = 5;WITH tree AS ( SELECT ChildId, ParentId, 1 TreeLevel FROM @Temp WHERE ParentId = @Id --UNION ALL --SELECT T.ChildId, -- Temp.ParentId, -- TreeLevel + 1 --FROM @Temp Temp -- INNER JOIN tree t -- ON t.ChildId = temp.ParentId )Select * FROM tree[/code]If I pass in 5 I really need to somehow get that in the childId field so I can treat it like a recursive query. I can't quite figure out how to get the results like this5-6,75- 4,3,1

Viewing all articles
Browse latest Browse all 3145

Trending Articles