CTE to get all children (descendants) of a parent
This should do it:
WITH MyTest as
(
SELECT P.ProductID, P.ParentID, CAST(P.ProductID AS VarChar(Max)) as Level
FROM Products P
WHERE P.ParentID = 0
UNION ALL
SELECT P1.ProductID, P1.ParentID, CAST(P1.ProductID AS VarChar(Max)) + ', ' + M.Level
FROM Products P1
INNER JOIN MyTest M
ON M.ProductID = P1.ParentID
)
SELECT * From MyTest
And here's the updated SQL Fiddle.
Also, check out this link for help with CTEs... They're definitely good to know:
Hope this does the trick!
;With Parents(ProductId, ParentId, Level, levels)
As(
Select ProductId, ParentId, 0,
cast(ltrim(str(productId,8,0)) as varchar(max))
From Products
Where ParentId = 0
Union All
Select p.ProductId, p.ParentId,
par.Level + 1,
cast( levels + ', ' + ltrim(str(productId,8,0)) as varchar(max))
From Products p
Join Parents par
On par.ProductId = p.ParentId
)
Select * From Parents
Order By Level