Expand a bill of materials without looping
Trace a recursive CTE through a component graph, multiply quantities along each path, and stop revisiting a node on the same path.
What you are trying to do
A planner needs total component quantities for one assembly. A component can appear through more than one branch, so each route contributes to the final quantity. Run the self-contained example in one SQL Server session.
Work through it
- Read
Componentas the edge list. Each row says how many child units one parent needs. - Read the anchor row in
Explosionas depth zero with one unit of the root assembly. - For each recursive pass, join the current item to its children and multiply the quantity accumulated so far by
QtyPer. - Follow
PathandCHARINDEX. The edge from item 400 back to 100 is skipped because 100 is already on this path. A node reached on a different path still contributes separately. - Check that item 400 totals 10 units. The two routes contribute 2 times 3 and 1 times 4.
- Review Microsoft's recursive CTE rules, including matching anchor and recursive column types and the statement-level recursion limit. Microsoft Learn
Check your work
The query returns item 200 with quantity 2, item 300 with quantity 1, and item 400 with quantity 10. It terminates despite the cycle in the edge list. MAXRECURSION 12 is a guard for this statement, while the path check prevents this sample cycle.
Practice SQL
Open in SQL Flow;WITH Component AS (
SELECT ParentId, ChildId, QtyPer
FROM (VALUES (100, 200, 2), (100, 300, 1), (200, 400, 3), (300, 400, 4), (400, 100, 1)) AS e(ParentId, ChildId, QtyPer)
), Explosion(ItemId, Depth, ExtendedQty, Path) AS (
SELECT CAST(100 AS int), CAST(0 AS int), CAST(1 AS decimal(18, 4)), CAST('/100/' AS varchar(80))
UNION ALL
SELECT c.ChildId, e.Depth + 1, CAST(e.ExtendedQty * c.QtyPer AS decimal(18, 4)), CAST(e.Path + CONVERT(varchar(10), c.ChildId) + '/' AS varchar(80))
FROM Explosion AS e
INNER JOIN Component AS c ON c.ParentId = e.ItemId
WHERE CHARINDEX('/' + CONVERT(varchar(10), c.ChildId) + '/', e.Path) = 0
)
SELECT ItemId, SUM(ExtendedQty) AS RequiredQty
FROM Explosion
WHERE Depth > 0
GROUP BY ItemId
ORDER BY ItemId
OPTION (MAXRECURSION 12);
Knowledge check
Commands in this lesson
Next lesson Compare window frames and rank tied results