Fix SQL Server Error 320 by changing the MAXRECURSION setting or rewriting your recursive CTE to use a self-join instead of a recursive UNION ALL. This error happens because a Common Table Expression (CTE) is infinitely looping or hitting the default recursion limit of 100.
What This Achieves
This guide explains how to resolve Error 320, a common but often confusing issue in SQL Server when working with hierarchical data. The error typically occurs when a Recursive Common Table Expression (CTE) (often called a recursive CTE or WITH clause) continues to recurse without a termination condition, or when it simply exceeds the default limit of 100 recursive calls allowed by SQL Server.
By following these steps, you will either extend the limit to allow your query to complete or, more importantly, identify and fix the logical error in your query that causes it to loop infinitely. This ensures your reporting and data processing scripts run reliably.
What You'll Need
- SQL Server Management Studio (SSMS) or a similar client tool (like Azure Data Studio) capable of running Transact-SQL scripts.
- Write permissions on the database or the server where the error is occurring, as the fix involves altering a session setting or modifying the query.
- A basic understanding of CTEs, specifically the
UNION ALLstructure used to recurse (Anchor member + Recursive member).
Step-by-Step
- Identify the problematic query. Locate the script or stored procedure that is throwing Error 320. The error message will usually point to the specific line number where the recursive CTE is defined.
- Analyze the CTE structure. A recursive CTE requires two parts: an anchor member (the starting point) and a recursive member that references the CTE itself. The most common cause of a limit error is a missing termination condition in the recursive member. Check the
WHEREclause of your recursive member. Is it filtering for a null value or a specific ID that stops the recursion? If that filter is missing or incorrect, the query will recurse infinitely. - Check for missing or incorrect joins. If your CTE is using a self-join in the recursive member rather than a recursive
UNION ALL, you might encounter this error if the join logic does not reduce the dataset size with each pass. Ensure the join is pulling back only the rows that need to be processed in the next iteration. - Option A: Increase the limit (Temporary Fix). If you are confident the query is correct and simply needs more iterations, you can temporarily override the default limit of 100. Add the
OPTION (MAXRECURSION 0)hint to the end of yourWITHclause. This sets the limit to infinite, allowing the query to run as long as it needs to. Warning: Do not use this in production environments without careful testing, as a bug in your logic could cause the server to hang indefinitely. - Option B: Increase the limit (Specific Fix). To be more precise, you can set a specific, higher limit instead of 0. Add
OPTION (MAXRECURSION 1000)(or whatever number you need) to the end of yourWITHclause. This allows you to control the recursion depth while still protecting the server from a runaway query. - Option C: Rewrite the query (The Best Fix). The most robust solution is to fix the query logic. If the query is using a recursive CTE to traverse a hierarchy, try rewriting it to use a standard self-join query. A self-join on the parent/child ID columns is often more efficient and less prone to the recursion limits of a CTE.
- Test the fix. Run the modified script. If you used Option A or B, verify that it returns the expected number of rows. If you rewrote the query, check the results against a known-good dataset to ensure accuracy.
Common Mistakes
- Confusing the error with a missing comma. While Error 320 is specific to recursion, it is often confused with Error 156 (Incorrect syntax near the keyword 'UNION') if a comma is missing between the anchor and recursive members in the CTE. Always verify the syntax around the
UNION ALLstatement. - Using
UNIONinstead ofUNION ALL. SQL Server typically requiresUNION ALLfor recursive CTEs. UsingUNION(which removes duplicates) is not supported in this context and will likely cause a syntax error, which can be misdiagnosed. - Ignoring the termination condition. The most frequent logical error is simply forgetting to filter the recursive member so it eventually becomes empty. Without this filter, the
WHEREclause is effectively ignored, and the query proceeds to the next iteration with the same data. - Hardcoding the recursion depth. In complex reporting scenarios, it is tempting to use a
WHILEloop and a temporary table to simulate recursion. While this works, it is often more complex to write and maintain than a proper recursive CTE.
Tips
- Use
SET STATISTICS IO ON;. Before running a recursive query, enable this setting. It shows you how many logical reads the query performs. High read counts in a recursive CTE can indicate inefficiency, such as failing to filter rows properly in each iteration. - Test with small datasets first. When debugging a recursive CTE, create a test table with a small, known hierarchy (e.g., 5 levels deep) and run your query against it. This makes it much easier to spot if the query is looping or missing data.
- Check for circular references. Ensure your data does not contain a circular reference (e.g., a parent pointing to its own child, who points back to the parent). This will cause the recursion to loop forever once it hits that cycle.
- Consider the data type. Ensure that the columns used in the join conditions of the recursive member have compatible data types. Implicit conversions can sometimes cause unexpected behavior in recursive steps.
Troubleshooting
- If the query still fails after adding
OPTION (MAXRECURSION 0), check for a circular reference. If your query loops infinitely even with no limit, it means your data has a cycle (A -> B -> A). You must clean your data or modify your query to handle this specific case, as a hard limit cannot fix a logical data error. - If you are getting a timeout error instead of Error 320. This might indicate the query is running very slowly or is stuck in an infinite loop. Use the Activity Monitor in SSMS to check the CPU and Blocking status of your session. You may need to kill the session (right-click the session > Kill).
- If you are on a newer version of SQL Server. The behavior of CTEs has been updated. If you are seeing unexpected results, ensure you are using a version of SQL Server that supports the specific syntax you are employing (e.g., recursive CTEs were introduced in SQL Server 2005).
- If you are using a stored procedure. The
OPTION (MAXRECURSION)hint must be added inside the body of the stored procedure, not at the end of the CREATE PROCEDURE statement. It must be placed after theWITHclause and before theASkeyword of the query.
Frequently Asked Questions
What does the error message mean?
The error means that your query tried to recurse more than the allowed number of times. By default, SQL Server allows a maximum of 100 recursive calls within a single CTE.
Is it safe to set MAXRECURSION to 0?
It is safe for testing and development, but risky in production. If your query has a bug, setting the limit to 0 allows the bug to run forever and consume all available server resources (memory and CPU).
Can I change the limit permanently?
No, the MAXRECURSION setting is a session-level option. It resets every time you connect to the server. You must add the hint to your query every time you run it.
Why does my CTE return fewer rows than expected?
This is often due to the termination condition being too strict (filtering out valid rows) or too loose (allowing the query to stop prematurely). Double-check the logic of your WHERE clause in the recursive member.
Can I use a cursor instead of a CTE?
You can, but it is generally not recommended. Cursors are resource-intensive and harder to read and maintain than a well-written recursive CTE. CTEs are optimized for this specific type of operation.