🗄️ SQL Server: Fix a Recursive CTE Hitting the Default 100-Level Cap
A recursive common table expression carries an implicit MAXRECURSION limit of 100 whenever a query doesn’t specify OPTION (MAXRECURSION n) explicitly – a safety net meant to catch an unintentionally infinite recursive query, like a self-referencing hierarchy with an accidental cycle. That same default applies just as strictly to a perfectly correct, intentionally deep hierarchy – an org chart, a bill-of-materials tree, a category structure – that simply happens to be more than 100 levels deep in real data, even though nothing about the query itself is wrong at all.
🔎 The Problem
WITH CategoryTree AS (
SELECT Id, ParentId, Name, 1 AS Depth FROM Categories WHERE ParentId IS NULL
UNION ALL
SELECT c.Id, c.ParentId, c.Name, t.Depth + 1
FROM Categories c JOIN CategoryTree t ON c.ParentId = t.Id
)
SELECT * FROM CategoryTree;
-- Msg 530: The statement terminated. The maximum recursion 100 has
-- been exhausted before statement completion.
-- (the real category tree is 118 levels deep, and that's correct data)
✅ The Fix
- Add OPTION (MAXRECURSION n) with a deliberately chosen limit higher than the deepest legitimate hierarchy the data can produce, or MAXRECURSION 0 to remove the limit entirely if you’re taking on responsibility for catching a genuine infinite cycle some other way.
- If removing the limit entirely, add a defensive cycle check inside the recursive CTE itself (tracking visited IDs in a path column and filtering out any path that revisits a node), so a genuinely cyclic data error still fails fast and visibly instead of being caught only by the now-disabled recursion cap.
- Confirm the actual maximum depth in the real data before choosing a replacement limit, so the new MAXRECURSION value is a deliberate, documented decision about this specific hierarchy rather than an arbitrary large number picked to make the error go away.
🚨 Why This Is Dangerous
Raising MAXRECURSION to an enormous number without adding the companion cycle-detection logic removes the one safety net that would otherwise catch a genuine data error – an accidental self-reference creating a true infinite loop – turning a fast, clear error into a query that can run indefinitely and tie up a connection and server resources instead.
100 levels of recursion isn’t a limit on your data – it’s SQL Server’s default guess about how deep a correct hierarchy should ever need to go, and a guess is exactly the kind of thing you’re allowed to correct.



