Search code examples
sqlsql-servercursorrbar

SQL Server : call stored procedure with side effects for each row without using a cursor


Before you say this is identical to SQL Call Stored Procedure for each Row without using a cursor let me clarify my question:

The stored procedure does have side effects. In fact, it's all about those side effects, as the results of each call influence further processing.

Think of it like this: the table contains rule definitions, and the proc executes those rules literally RBAR, making changes to another table.

Under those conditions I do not see how a set operation is possible, CROSS APPLY probably can't be used because of side effects, but it's also not needed, since I'm not really joining the rule table with any results.

If the solution is really RBAR, should I still try to avoid using CURSOR? Is using WHILE with READ TOP 1 WHERE Key > @Key a better solution? Why?

The more I searched, the more I came to the conclusion that fast_forward read_only cursor is the simplest and fastest solution.


Solution

  • cursors are inherently bad

    No. Cursors are easily misused, and tend to be leapt upon by people new to SQL because they're from a procedural background and haven't even heard of "set-based". Cursors have their place, and if you've assessed the available approaches and concluded that cursors are a good fit, I'd say use one.

    Using a WHILE loop to hide the fact that what you're really doing is using a cursor is also something I'd recommend against.

    One final note - you mentioned fast_forward and read_only - but one other recommendation would be local - that way, if something goes wrong, at least the cursor is cleaned up when you exit whatever scope your cursor is running in - rather than persisting for the lifetime of the connection.