Is it possible to pass a parameter to the CTE, which selects node and then selects the parent to the root, where parentIdit is null?
In my code below, if I pass in a parameter that Rain Coats selects and then recurses the tree to the male carry, where it parentIdis null and selects all the nodes in this branch, including the child ones. Can someone help me with this please. My example just repeats and shows the depth
SQL example:
DECLARE @Department TABLE
(
Id INT NOT NULL,
Name varchar(50) NOT NULL,
ParentId int NULL
)
INSERT INTO @Department SELECT 1, 'Toys', null
INSERT INTO @Department SELECT 2, 'Computers', null
INSERT INTO @Department SELECT 3, 'Consoles', 2
INSERT INTO @Department SELECT 4, 'PlayStation 3', 3
INSERT INTO @Department SELECT 5, 'Xbox 360', 2
INSERT INTO @Department SELECT 6, 'Games', 1
INSERT INTO @Department SELECT 7, 'Puzzles', 6
INSERT INTO @Department SELECT 8, 'Mens Wear', null
INSERT INTO @Department SELECT 9, 'Mens Clothing', 8
INSERT INTO @Department SELECT 10, 'Jackets', 9
INSERT INTO @Department SELECT 11, 'Rain Coats', 10
;WITH c
AS
(
SELECT Id, Name,1 AS Depth
FROM @Department
WHERE ParentId is null
UNION ALL
SELECT t.Id, t.Name, c.Depth + 1 AS 'Level'
FROM @Department T
JOIN c ON t.ParentId = c.Id
)
SELECT * FROM c WHERE c.Id = 3
source
share