Sunday, August 10, 2008

Avoid Using Cursors

Always try to avoid cursors as they are an overhead to the engine. Instead try to write the same logic by using a temporary table or a table valued variable. This case is applicable to cases where the volume of data dealt is high. If the volume of data dealt is low try to use an inline table.

If the cursor cannot be avoided then check for the following scenarios

  1. SQL Server offers you several different types of cursors, each with its different performance characteristics. Always select the cursor with the least amount of overhead that has the features you need to accomplish your goals. The most efficient cursor you can choose is the fast forward-only cursor.
  2. When using a server-side cursor, always try to fetch as small a result set as possible. This includes fetching only those rows and columns the client needs immediately. The smaller the cursor, no matter what type of server-side cursor it is, the fewer resources it will use, and performance will benefit.
  3. When you are done using a cursor, don’t just CLOSE it, you must also DEALLOCATE it. Deallocation is required to free up the SQL Server resources used by the cursor. If you only CLOSE the cursor, locks are freed, but SQL Server resources are not. If you don’t DEALLOCATE your cursors, the resources used by the cursor will stay allocated, degrading the performance of your server until they are released

1 comment:

narayana p said...

It was so nice article. I was really satisfied by seeing this article. SQL server dba Online Training Bangalore