Reputation: 7525
Table Structure:
I Tried this:
select Id, Name from Color where ParentId=4
UNION
select Id, Name from Color where ParentId=(select Id from Color where ParentId=4)
Above approach is static in this case I have to know all the Ids. I'm looking something dynamic approach since I would have only Color's ParentId value.
As example: For ParentId=4 there are two records; Name Blue and Red their Id is 6 and 10 respectively. Now here, I need to get all the records where Id 6 and 10.
Upvotes: 4
Views: 3235
Reputation: 79969
Try this:
;WITH cte
AS
(
SELECT Id, Name, ParentId
FROM Color
WHERE ParentId = @parentIdValue
UNION ALL
SELECT c2.Id, c2.Name, c2.ParentId
FROM cte c1
INNER JOIN Color c2 ON c2.ParentId = c1.Id
)
SELECT * FROM cte;
Upvotes: 6