<![CDATA[Question I understand that I should avoid the use of SQL Server cursors in order to increase an application’s performance. Can you provide some ways that I might be able to avoid using cursors in my applications?
A SQL Server cursor should only be considered in situations where you need to scroll through a set of rows, and then based on criteria you specify, do something potentially different to each row (and in many cases even this can be done using a standard query). If what you need to do to each row is the same, then you should definitely avoid a cursor, and instead use a Transact-SQL query.
Keep in mind that one of the biggest benefits of using a relational database, such as SQL Server, is that is acts on an entire sets of records in one fell swoop. This results in very fast performance. But if you have to perform different actions on each different record, then you often have to use a cursor to accomplish your goal. Because records have to be examined one-at-a-time, cursors often result in poor performance.
While it is true that a query will always outperform a cursor (assuming they are performing the same task), this doesn’t always mean that you shouldn’t use a cursor in some cases. For example, sometimes I need to perform a fairly simple task on an occasional basis. In these cases, I often use a cursor because they are fairly easy to write, and because performance is not an issue for the task at hand.
On the other hand, if the task is repeated often, and performance is an issue, then you should avoid cursors if at all possible. Some ways to avoid cursors include:
- Rewriting the cursor as a normal query. Some people write cursors that perform the same task over and over on a set of records. This is a waste of server resources because this could be easily handled by a standard query. And even if what you need to do to each row is conditional on data in a row, you still may be able to to use a standard query using a CASE statement.
- Rewriting the cursor as a derived query. See this article for more information.
- Rewriting the cursor using temporary tables in a query. See this article for more information.
- Rewriting the cursor using table variables in a query (SQL Server 2000 or 2005).
If you find that you have to use a cursor, then try to use a FAST-FORWARD, READ-ONLY cursor, which is the cursor that uses the least resources. See these tips for speeding the use of cursors.]]>