I have a table similar to this structure:
TaskId: int PK
AssignedTo: varchar(50)
ParentTaskId: int FK nullable
ParentTaskId references TaskId.
The data in the table looks similar to this:
TaskId | AssignedTo | ParentTaskId
1 Jim NULL
2 Jim 1
3 Joe 2
4 John NULL
...
The crux of my issue is this: I need to query the table for all tasks assigned to Joe (which would return TaskId 3), but I also need to show the hierarchy for the found task, so I need to return Tasks 1, 2, and 3 from the above table.
I'm lost as to how do pull this data from SQL, either with one query or multiple queries.
Help please! Using SQL Server 2012.
Best Answer
For future posts, it's much better to provide
CREATE TABLE
andINSERT
statements like:That said, you can use a recursive common table expression (CTE) as in:
I only had sql-server2017 to test with, but afaik, recursive cte should be availible in 2008 as well