How to fix Error 465 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 465 – Recursive References Not Allowed in Subqueries

Why This Error Happens

Error 465 occurs when a Common Table Expression (CTE) or subquery references itself in a way that SQL Server’s query optimizer cannot resolve, typically due to a non-recursive CTE containing a self-reference or a view definition that indirectly calls itself. This is not caused by permissions or system corruption but by a logical flaw in T-SQL syntax where the recursive member of a query is malformed or missing the required UNION ALL anchor structure. It can also surface after migrating queries from older SQL Server versions where syntax leniency has been tightened in SQL Server 2025’s updated query parser.

Step-by-Step Resolution Guide

Step 1: Identify the Offending Query Object

  • Open SQL Server Management Studio (SSMS) and check the Activity Monitor or the error log at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG to find the exact query or stored procedure ID that triggered Error 465.
  • Run the following command to isolate the object:
SELECT object_name(objectid) FROM sys.dm_exec_query_stats 
CROSS APPLY sys.dm_exec_sql_text(sql_handle) WHERE text LIKE '%WITH%AS%'
  • Look specifically for nested CTEs or views calling themselves within the FROM clause.

Step 2: Correct the CTE or View Definition

  • If using a Common Table Expression, ensure the recursive CTE explicitly uses UNION ALL to separate the anchor member from the recursive member.
  • Verify that the recursive member does not reference the CTE name more than once in the FROM clause; SQL Server 2025 strictly enforces the “single self-reference” rule.
  • If the error originates from a nested View (View A calling View B, which calls View A), refactor the logic into a single unified query or a temporary table to break the circular loop.

Step 3: Update Compatibility Level and Rebuild

  • Since this is a fresh SQL Server 2025 instance, verify the database compatibility level is correctly set to 170 (or the current 2025 level) to ensure the parser is reading intended recursive logic correctly:
ALTER DATABASE [YourDB] SET COMPATIBILITY_LEVEL = 170;
  • Drop and recreate the specific Stored Procedure or View after applying the fix to clear any cached, corrupted execution plans associated with the faulty recursive logic.

Alternative or Verification Steps

  • To verify the fix, execute the query in isolation using SET SHOWPLAN_TEXT ON to ensure the execution plan generates without throwing the parser error before running it against production data.
  • If the error persists after fixing the syntax, use a Recursive CTE Depth Limiter (OPTION (MAXRECURSION 100)) to rule out an infinite loop scenario rather than a syntax parsing issue.