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?
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
On a side note… I’m not sure I like the idea of the table name being
table.