Reputation: 2729
I am writing a query which needs to return all child entries (and their children etc...) under any given parent ID.
For example:
SELECT id
FROM table
WHERE parent_id IN
(SELECT id
FROM table
WHERE parent_id IN
(SELECT id
FROM table
WHERE parent_id IN
(SELECT id
FROM table
WHERE code = 'A01')
)
)
As expected, this will only return a result set for the topmost SELECT
query. I could write a UNION SELECT
for each child level but that seems a tad clumsy...
Is there a way to add each individual result set from each nested query into my main set of results? Or should I take the clumsy option?
Upvotes: 0
Views: 2633
Reputation: 13419
Your problem is best solved with a recursive query. A great way to perform recursive queries in SQL Server 2005 or later is to use Common Table Expressions
;with cte as (
SELECT id, parent_id
FROM [table]
WHERE code = 'A01'
UNION ALL
SELECT t.id, t.parent_id
FROM [table] t
INNER JOIN cte
ON cte.id = t.parent_id
)
SELECT id
FROM cte
OPTION (MAXRECURSION 0);
On a side note... I'm not sure I like the idea of the table name being table
.
Upvotes: 3