Troubleshooting Guide: Error 336 – “Incorrect Syntax Near ‘%.*ls'” in SQL Server 2025
Why This Error Happens
This error typically occurs when a Common Table Expression (CTE) is defined using a WITH clause but is not properly terminated with a semicolon on the preceding T-SQL statement, causing the parser to misinterpret the query boundary. It can also happen when the CTE name conflicts with a reserved keyword, or when there is a syntax error inside the CTE body itself (such as a misplaced comma, missing column alias, or an unsupported clause like ORDER BY inside the CTE definition). Additionally, this can surface after upgrading to SQL Server 2025 if legacy scripts rely on deprecated parsing behavior that the new query processor no longer tolerates.
Step-by-Step Resolution Guide
Step 1: Verify Statement Termination Before the WITH Clause
- Check that the T-SQL statement immediately preceding your
WITHclause ends with a semicolon (;). - Example fix:
SELECT * FROM dbo.SomeTable;
WITH CTE_Name AS (
SELECT Column1, Column2 FROM dbo.AnotherTable
)
SELECT * FROM CTE_Name;
- Open SQL Server Management Studio (SSMS) 2025 and use
Ctrl+Shift+Fto reformat the query for easier visual inspection of missing terminators.
Step 2: Validate CTE Naming and Column List Syntax
- Ensure the CTE name does not use a reserved keyword (e.g., avoid naming a CTE
OrderorGroup). - Confirm the column list (if explicitly defined) matches the number of columns returned in the
SELECTinside the CTE body. - Example of correct syntax:
WITH SalesCTE (OrderID, TotalAmount) AS (
SELECT OrderID, SUM(Amount)
FROM dbo.Sales
GROUP BY OrderID
)
SELECT * FROM SalesCTE;
Step 3: Remove Unsupported Clauses Inside the CTE Definition
- Delete any
ORDER BYclause inside the CTE body unless paired withTOP,OFFSET, orFOR XML, as standaloneORDER BYis not permitted inside a CTE. - Check for stray commas or parentheses mismatches using the SSMS IntelliSense red squiggly-line indicators.
Step 4: Update SQL Server 2025 Cumulative Updates
- Navigate to
Control Panel > Programs > Programs and Featureson Windows Server 2025 / Windows 11 to confirm your current SQL Server build number. - Download and apply the latest Cumulative Update (CU) from the Microsoft Update Catalog, as early 2025 builds had known parser regressions affecting recursive CTEs.
- Restart the SQL Server (MSSQLSERVER) service via
services.mscafter patching.
Alternative or Verification Steps
- Run the corrected query in a new query window in SSMS and confirm it executes without red underline warnings or Error 336 in the Messages tab.
- If the error persists, isolate the issue by commenting out the CTE body and testing the inner
SELECTstatement independently to confirm it is valid outside the CTE wrapper.