SQL Flow Field Guide

Walk a dependency tree with a recursive CTE

Separate a recursive CTE's anchor from its recursive member and carry depth and path through each level.

What you are trying to do

A release tool needs every task downstream of root task 1, with the dependency depth and a readable path for review.

Work through it

  1. Read Dependencies as the inline edge list. ParentTaskId points from a prerequisite to its dependent task.
  2. Start at task 1 in the anchor member with depth zero.
  3. Follow the recursive join from each discovered task to its children. The recursive member adds one depth level and extends the path.
  4. Check the depth-first result and the MAXRECURSION safety bound.
  5. This sample is acyclic. MAXRECURSION limits runaway recursion but does not detect or repair cycles.

Check your work

The result has exactly four rows: task 1 at depth 0 with path /1/; task 2 at depth 1 with path /1/2/; task 3 at depth 1 with path /1/3/; and task 4 at depth 2 with path /1/2/4/.

Practice SQL

Open in SQL Flow
WITH Dependencies AS (
    SELECT TaskId, ParentTaskId, TaskName
    FROM (VALUES (1, CAST(NULL AS int), N'Release'), (2, 1, N'Build'), (3, 1, N'Test'), (4, 2, N'Package')) AS v(TaskId, ParentTaskId, TaskName)
), TaskTree AS (
    SELECT TaskId, ParentTaskId, TaskName, 0 AS Depth, CAST(CONCAT('/', TaskId, '/') AS varchar(100)) AS Path
    FROM Dependencies
    WHERE TaskId = 1
    UNION ALL
    SELECT child.TaskId, child.ParentTaskId, child.TaskName, parent.Depth + 1, CAST(CONCAT(parent.Path, child.TaskId, '/') AS varchar(100))
    FROM Dependencies AS child
    INNER JOIN TaskTree AS parent ON child.ParentTaskId = parent.TaskId
)
SELECT TaskId, ParentTaskId, TaskName, Depth, Path
FROM TaskTree
ORDER BY Depth, TaskId
OPTION (MAXRECURSION 20);

Knowledge check

Commands in this lesson

Next lesson Page with a stable keyset cursor