SQL Server Error 328: Cursor Plan Could Not Be Generated
In this article
SQL Server error 328 ("A cursor plan could not be generated for the specified statement because the cursor requires a dynamic plan") means the optimizer could not build a plan that supports the cursor you asked for. The usual fix is to stop forcing a server-side cursor you do not need: either declare the cursor with STATIC, KEYSET or FAST_FORWARD instead of leaving it dynamic, or replace the cursor with a set-based query or a client-side cursor. The error is a planning error, not a permissions or corruption problem, so nothing is broken - SQL Server is refusing because the statement behind the cursor cannot be executed under dynamic cursor semantics.
Cursor options can be named slightly differently depending on the SQL Server version and how you connect, so treat the exact wording in your client as a guide rather than a fixed label.
What You'll Need
- The exact T-SQL batch or stored procedure that fails, so you can see the
DECLARE ... CURSORstatement in full. - Permission to run the query and, if needed, to alter the procedure or query text (ALTER rights on the procedure or database, depending on where the cursor lives).
- A way to test changes somewhere safe - a development or staging copy of the database is ideal before you change production code.
- Access to the statement text inside the cursor, including any
UNION,DISTINCT,GROUP BY,COMPUTE,ORDER BYon a non-unique key, or use of a view with those constructs, because these are the usual triggers. - Optional but useful: the estimated execution plan from the client (SSMS or Azure Data Studio) so you can see whether the optimizer is choosing a plan it cannot make dynamic.
Step-by-Step
- Reproduce the error and capture the exact statement. Run the failing batch in SQL Server Management Studio or Azure Data Studio and read the full message. Confirm it is error 328 and not a related cursor error such as 16943 (cursor already exists) or 16929 (cursor is read-only). Write down the
DECLARE cursor_name CURSORline and theSELECTthat followsFOR. - Find the offending SELECT. Dynamic cursors are the default when you do not name a cursor type, and they cannot be generated for statements containing constructs the engine cannot reconcile with dynamic scrolling. Look for
UNION,UNION ALL,DISTINCT,GROUP BY, aggregate functions without grouping,HAVING,COMPUTE,COMPUTE BY, or aSELECTfrom a view that itself contains these. Any one of them is enough to trigger the error. - Switch to a cursor type that does not require a dynamic plan. Change the declaration to
STATIC(a snapshot of the rows, safest and most predictable for read-only loops),KEYSET(rows can be updated and the key is stable), orFAST_FORWARD(forward-only, read-only, and the lightest option when you only move forward). For example, replaceDECLARE c CURSOR FOR SELECT ...withDECLARE c CURSOR FAST_FORWARD FOR SELECT ....FAST_FORWARDis the usual first choice for procedures that simply iterate a result set. - Re-run the batch. If the error disappears, the problem was the dynamic plan requirement and you are done apart from checking that the cursor still behaves as the code expects -
FAST_FORWARDis read-only and forward-only, so anyUPDATE ... WHERE CURRENT OFagainst that cursor will fail and should useKEYSETorDYNAMIC-compatible alternatives instead. - If the cursor must stay dynamic, rewrite the SELECT. Remove the incompatible construct rather than the cursor. Split a
UNIONinto separate cursors or into a temp table fed by two inserts; replaceDISTINCTwithGROUP BYover a key column or with aROW_NUMBER()filter; materialise a grouped result into a temp table (SELECT ... INTO #work FROM ... GROUP BY ...) and declare the cursor over#work. A simple single-table or single-join SELECT over a table is what dynamic cursors handle best. - Check whether the cursor is server-side or client-side. The API cursor type requested by your application (for example ADO, ODBC or an ORM) can also cause this error. If the app asks for a dynamic server-side cursor and the statement cannot support it, request a static or forward-only cursor from the connection or command object, or set the cursor location to client-side so the driver fetches the rows and scrolls locally.
- Test the corrected code against realistic data volume. Cursors over large tables are slow regardless of type, and a static cursor copies the result set. Run the fixed batch on a copy of the data, check the row counts and timing, and make sure the loop still processes every row exactly once.
- Deploy the change and update source control. Apply the altered procedure or query to production, then verify by executing it once in a transaction you roll back, so you confirm success without side effects. Record what you changed (cursor type, rewritten SELECT, or client setting) so the next person hitting error 328 finds the fix quickly.
Common Mistakes
- Assuming the error is a corruption or licensing fault. It is a planning limitation. No repair, restart or reinstall is needed, and restarting the instance wastes time and disrupts users.
- Adding
OPTION (RECOMPILE)or query hints as the first attempt. Plan hints rarely change whether a cursor can be generated, because the restriction comes from the statement's shape, not from a bad plan choice. - Changing the cursor to
FAST_FORWARDand leaving positioned updates in place.FAST_FORWARDcursors are read-only, soWHERE CURRENT OFupdates will fail. UseKEYSETif the loop must update the row it is sitting on. - Rewriting the procedure but not the app connection settings. If the application requests a dynamic cursor directly, the server error can persist even after the T-SQL is fixed. Both sides must agree on the cursor type.
- Forgetting nested cursors and views. A view that contains a
UNIONorGROUP BYwill fail the same way as an inline SELECT. Check every object the cursor select reads from. - Leaving the cursor open on an error path. Wrap the loop with proper
CLOSEandDEALLOCATEhandling, otherwise the next run can hit a different cursor error and mask the real problem.
Tips
- Prefer set-based SQL over cursors entirely. Most row-by-row loops can be replaced with
UPDATE ... FROM,MERGE, or a single statement, which removes this class of error and is dramatically faster. - When you genuinely need a cursor, declare it
LOCAL FAST_FORWARDin stored procedures. Local scope avoids name collisions between concurrent sessions. - Use
STATICwhen you want a stable snapshot and the result set is modest, since it is the least surprising cursor type for reporting loops. - Test after changing data types or indexes on the underlying tables: a new index can change the plan shape and, occasionally, whether a dynamic cursor is viable.
- Keep cursor
SELECTstatements small and simple. If the logic is complicated, do the work into a temp table first and loop over that.
Troubleshooting
The error appears only in the application, not in SSMS. This points to the driver requesting a dynamic server-side cursor. Change the cursor type the connection or command requests (forward-only, static), or move cursor processing to the client side.
The error persists after changing the cursor type. Check for a nested cursor inside the loop, or a cursor declared inside dynamic SQL that you have not edited. Search the procedure text for every CURSOR keyword.
A different cursor error appears next, such as the cursor being read-only. You have moved to a cursor type that does not support the operation you are performing. Match the type to the operation: STATIC or FAST_FORWARD for read-only loops, KEYSET for positioned updates where the key is unique.
The SELECT cannot be simplified because the view is shared. Materialise the view output into a temp table with unique keys, put a unique index on it, and declare the cursor over the temp table. This sidesteps the incompatible construct without changing the shared view.
Performance collapses after switching to STATIC. That is expected on large result sets because the full set is copied at open. Reduce the rows the cursor selects with a tighter WHERE clause, or replace the loop with set-based SQL.
Frequently Asked Questions
Is SQL Server error 328 a serious problem?
No. It is a planning restriction on a specific cursor statement. Your database and data are not damaged, and only the statement using that cursor is affected.
Does changing to FAST_FORWARD always fix it?
It fixes it in most read-only loops, because FAST_FORWARD does not need a dynamic plan. If your loop updates rows through the cursor, you may need KEYSET instead, and the SELECT may still need simplifying.
Why does a UNION inside a cursor cause this error?
A dynamic cursor needs a plan that supports scrolling and reflecting changes. Set operations such as UNION and DISTINCT produce a result the engine cannot map back to base rows reliably, so it refuses to build a dynamic plan.
Can I keep my dynamic cursor and just add a hint?
Usually not. Query hints change plan choices, not the structural limits on dynamic cursors. Rewriting the SELECT or changing the cursor type is the reliable route.
Will a client-side cursor avoid the error?
Often yes, because the server then returns a plain result set and the driver scrolls it locally. The trade-off is that the whole result set may be transferred to the client.
Do I need to restart SQL Server after the fix?
No. Changing the procedure or query takes effect on the next execution. Restarting the instance has no bearing on cursor plan errors.