SQL Server error 565 indicates a stack overflow occurred within the SQL Server process, typically caused by deeply nested recursive queries, excessive stored procedure nesting, or insufficient stack memory allocation. This error halts the current batch and may require immediate troubleshooting to prevent recurring crashes. To resolve it, identify and modify the problematic query or procedure, increase the server's stack size if necessary, and monitor for recurrence.
What You'll Need
- Access to SQL Server Management Studio (SSMS) or equivalent query tool
- Appropriate permissions to view error logs, modify queries, and adjust server configuration (sysadmin or equivalent)
- Access to the Windows Server hosting SQL Server (if adjusting stack size via registry)
- SQL Server Error Logs (accessible via SSMS or file system)
- Optional: SQL Profiler or Extended Events for tracing problematic batches
Step-by-Step
- Locate the error details in the SQL Server Error Log. Open SSMS, connect to the instance, navigate to Management > SQL Server Logs, and find the most recent entry containing "Error: 565" or "stack overflow". Note the exact time and any associated SPID or batch text.
- Identify the problematic query or stored procedure. If the error log includes the batch text, review it for recursive common table expressions (CTEs), deeply nested views, or stored procedures that call themselves or each other excessively. If not, use SQL Profiler or Extended Events to capture the batch that triggered the error by setting up a trace for RPC:Completed and SQL:BatchCompleted events around the time of the error.
- Analyze the query for recursion depth. For recursive CTEs, check the termination condition and ensure it will resolve within a reasonable number of iterations (typically under 100). For stored procedures, review the call stack to avoid circular or deep nesting—refactor to use iterative logic or temporary tables if nesting exceeds 32 levels (the default stack limit for many procedures).
- Modify the query or procedure to reduce stack usage. Examples: - Add a MAXRECURSION option to recursive CTEs (e.g., OPTION (MAXRECURSION 20)). - Replace recursive logic with a WHILE loop or table-valued function. - Break down complex nested views into simpler, materialized steps using temporary tables or table variables. - Ensure stored procedures have a clear exit condition and avoid calling themselves unless absolutely necessary with strict depth limits.
- Test the changed query or procedure in a non-production environment. Execute it with realistic data volumes and monitor for performance and correctness. Use SET STATISTICS IO, TIME ON to validate behavior.
- If the issue persists after query optimization, consider increasing the server's stack reserve size via the Windows Registry (only if absolutely necessary and after query optimization fails):
- Open Registry Editor (regedit).
- Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\
\MSSQLServer\Parameters. - Add a new DWORD value named "StackSize" (or modify if exists) and set it to a higher value in KB (e.g., 1024 for 1MB, default is often 256KB). - Restart the SQL Server service for the change to take effect. > Note: This step is rarely needed and should only be done after confirming the issue is not query-related. Increasing stack size masks the symptom but does not fix poor query design. - Monitor the SQL Server Error Log and system metrics after deployment. Watch for recurrence of error 565 and check for performance degradation. If the error returns, repeat the analysis to ensure the root cause was fully addressed.
Common Mistakes
- Assuming error 565 is always due to insufficient memory and immediately increasing stack size without checking the query—this often leads to recurring crashes and wasted effort.
- Overlooking indirect recursion, such as Procedure A calling Procedure B, which calls Procedure A, creating a cycle that exceeds stack limits.
- Using MAXRECURSION 0 to allow infinite recursion, which guarantees a stack overflow and should only be used with extreme caution and guaranteed termination logic.
- Failing to test changes under load; a query may work with small data sets but overflow with larger ones due to increased recursion depth.
- Modifying the registry incorrectly (e.g., wrong path, wrong data type) which can prevent SQL Server from starting.
Tips
- Always set a reasonable MAXRECURSION value on recursive CTEs during development—never rely on the default (100) without verifying it's safe for your data.
- Use the query execution plan to detect unexpected recursion or excessive nested loops; look for operators like "Recursive Join" or "Nested Loops" with high estimated rows.
- Enable the "trace flag 2551" temporarily to get more detailed stack information in the error log (use DBCC TRACEON(2551, -1) under guidance—this is advanced and requires restart).
- Keep stored procedure nesting shallow; aim for fewer than 5 levels unless unavoidable, and document any deep calls.
- After fixing the issue, add error handling (TRY...CATCH) to log recursive depth or iteration counts in critical procedures to catch regressions early.
Troubleshooting
If error 565 persists after query changes:
- Verify the change was deployed to the correct instance and database—check for multiple instances or missed deployments.
- Check if a scheduled job, trigger, or replication process is executing the problematic code—review SQL Agent jobs and DDL triggers.
- Collect a full memory dump during the next occurrence (if feasible) and analyze with WinDbg or submit to Microsoft Support for deep stack analysis.
- Ensure no recent updates or patches changed behavior—review patch history and known issues for your SQL Server version.
- As a last resort, temporarily reduce MAXDOP to 1 to see if parallelism exacerbates the issue, though this is rarely the root cause.
If the server becomes unresponsive or crashes repeatedly:
- Dedicated administrator connection (DAC) may still allow access—use sqlcmd -A to connect and run diagnostics.
- Check Windows Event Viewer for application or system logs that might indicate hardware issues (e.g., memory faults).
- If all else fails, failover to a secondary node (if in an AG or cluster) or restore from a known-good backup after documenting the failure state.
Frequently Asked Questions
Can error 565 be caused by hardware issues?
While extremely rare, underlying memory corruption or faulty RAM could theoretically contribute to stack-related crashes, but error 565 is almost always due to software/query design. Run Windows Memory Diagnostic if hardware is suspected.
Is it safe to set MAXRECURSION to 0?
No—setting MAXRECURSION to 0 removes the safety limit and will cause a stack overflow if the recursive CTE does not terminate perfectly. Only use it if you have mathematically proven termination and absolute control over data.
Does increasing the stack size via registry affect all instances on the server?
No—the StackSize registry value is instance-specific under the MSSQLServer\Parameters key for that instance. Named instances have separate paths.
How can I prevent error 565 in development?
Enforce code reviews for recursive logic, set MAXRECURSION explicitly in all CTEs, and use static analysis tools or linters that flag deep procedure nesting or missing termination conditions.
Will fixing error 565 improve query performance?
Not directly—fixing the overflow prevents crashes, but the rewritten query (e.g., using a WHILE loop instead of recursion) may be faster or slower depending on the case. Always test performance after changes.
Is error 565 the same as a stack overflow in .NET applications?
Both involve exceeding the call stack limit, but error 565 occurs inside the SQL Server executable (sqlservr.exe), not in managed code. The troubleshooting approach differs significantly.