.: Eliminating cursor in SQL Server

By:Marin Kostadinovic

Category:Home / Computers / Software

We all know how cursors are slow and how badly they tend to issue a lock on part of the table, or on the whole table, during its execution. To explain exactly what is going on, and what we can do to optimize the performance, here is an example:



Table t_Customers has 3000 records.



Table t_Orders has 1 to 100 records for each record in t_Customers table, making it a table with 65000 records.



We want to print all of the orders for customers that had orders in the last month. There are several solutions that we can use and first one is usage of the cursor:



Declare
@nCustID Int
, @cCustName varchar(30)
, @nOrdNo Int



Declare curCusOrd For

Select
C.CustID
, C.CustName
, O.OrderNo

From
t_Customers C
Left Join t_Orders O
On C.CustID = O.CustID

Where
O.OrderDate >= DateAdd( month, -1, GetDate() )



Fetch Next From curCusOrd

Into
@nCustID
, @cCustName
, @nOrdNo


While @@Fetch_Status = 0
Begin


/*
Print Order
*/


Fetch Next From curCusOrd
Into
@nCustID
, @cCustName
, @nOrdNo


End



Close curCusOrd

DeAllocate curCusOrd



In example above, cursor will lock part of each table, or both tables as a whole, while orders are printed. On top of this, a lot of disk activities will be done in order to scan both t_Customers and t_Orderd tables, resulting a very slow performance.



The first alternative is to create a temporary table, that will contain all key columns, and then to use it as a pointer instead of cursor. For a small dataset we can easily eliminate a slow performing and memory intense cursor with a temporary table. Here is a same procedure done with temporary table:



Declare
@nCustID Int
, @cCustName varchar(30)
, @nOrdNo Int
, @nRowCnt Int
, @nRows Int



Create Table #tempCustOrd

(
CusOrdID IDENTITY (1, 1) Primary key Not Null
, CustID Int Not Null
, CustName varchar(30) Not Null
, OrderNo Int

)



Insert #tempCustOrd

Select
C.CustID
, C.CustName
, O.OrderNo

From
t_Customers C
Left Join t_Orders O
On C.CustID = O.CustID

Where
O.OrderDate >= DateAdd( month, -1, GetDate() )



Select
@ nRowCnt = 1
, @nRows = Count(*)

From #tempCustOrd



While @nRowCnt <= @nRows
Begin


Select
C.CustID
, C.CustName
, O.OrderNo
From #tempCustOrd
Where CusOrdID = @nRowCnt


/*
Print Order
*/


Select @nRowCnt = @nRowCnt + 1


End



Drop Table #tempCustOrd



Locks that were issued on t_Customers and t_Orders are now eliminated, but the price is a lot of disk activities, along with the potential locking of whole temporary table. All of this adds up to a lousy performance, especially on large or long-running operations.



The third alternative is to use a SQL Server Table variable. This is a variable that can be used in stored procedures, functions and batches. They have no permanent life outside of the batch that contains them. They're cleaned up automatically at the end of the batch and you don't need to worry about name conflicts with anything outside of this scope. Within its scope, a table variable behaves like a permanent table.



Now lets take a look at our example using a Table variable. It is almost identical as the temporary table example. Only difference is the table declaration and the fact that you do not need to drop it after you’re done using it. So here is our code with Table variable:



Declare
@nCustID Int
, @cCustName varchar(30)
, @nOrdNo Int
, @nRowCnt Int
, @nRows Int



Declare @t_CustOrd Table

(
CusOrdID IDENTITY (1, 1) Primary key Not Null
, CustID Int Not Null
, CustName varchar(30) Not Null
, OrderNo Int

)



Insert @t_CustOrd

Select
C.CustID
, C.CustName
, O.OrderNo

From
t_Customers C
Left Join t_Orders O
On C.CustID = O.CustID

Where
O.OrderDate >= DateAdd( month, -1, GetDate() )



Select
@ nRowCnt = 1
, @nRows = Count(*)

From @t_CustOrd



While @nRowCnt <= @nRows
Begin


Select
C.CustID
, C.CustName
, O.OrderNo
From @t_CustOrd
Where CusOrdID = @nRowCnt


/*
Print Order
*/


Select @nRowCnt = @nRowCnt + 1


End



Table variable resides in memory, there is no disk I/O, it does not use tempdb, therefore eliminating all of the locks. Execution is fast; it takes 1/5 of time to complete the same job then it would using cursors.



As you can expect there are limitations:

- Server physical memory. Always keep your server memory in mind when you work with Table variable

- You can not create index on the Table variable. If you need to work with a large amount of data with many indexes, use a temporary table instead of a table variable

- The table scheme on Table variable is static. If you need to modify it in the course of a batch, use a temporary table instead.

- You can not use Select Into statement on a Table variable



As a general rule of thumb, you should use table variable any time that your temporary data is of reasonable size and is only used a few times. As your temporary data grows in size, complexity, and reuse, a temporary table will be more appropriate. Using execution plans, SQL Profiler, and performance counters available to monitor what's going on inside of your stored procedures, you can code the alternatives and test them when there's any doubt.

Digg del.icio.us Blink Stumble Spurl Reddit Netscape Furl

Article keywords: sql server, eliminating cursor, table type, table variable

Article Source: http://www.articles32.com

Marin Kostadinovic is in the database development/architecture and website design business for more than 20 years. He is currently mastering www.website-hosting-development.com” >Website Hosting and Development and www.dimm-is.com >DIMM Info Systems Inc. websites.





.: New Software Articles

1). What Your Spouse Might Not Want You To Know
Is your spouse or significant other extremely secretive about their computer habits?

2). Why Buy Anti Spyware Software When I Can Download it Free?
Many Spyware software packages are being sold on the Internet. Many other packages are listed for free. Why should you pay for something that might be free?

3). Free Spyware Adware Remover
Computers need routine maintenance as well as systems checks in order to be in good condition at all times. This can be done by getting the proper software or sending the unit to the shop.

4). Getting Free Internet Security for Your Computer
Surfing the Internet nowadays can be very dangerous. With all the viruses, spywares, adwares, identity thieves and hackers circulating for surfers to victimize, opening and downloading an attachment sent by your friend can be very scary.

5). What Are Your Children Doing Online?
In the Internet age, our children use the computer as much as or maybe more than their parents do. Kids use the Internet to do homework, play video games, converse with their friends and more.

6). Safe Guard Your Critial Business Documents
All types of commercial places, whether in the private, public or the government sector are now increasingly using computers for various possible functions.

7). How Folder Hider Software Works
Nowadays, a computer is being increasingly used in all types of settings, whether it is an office, a corporate house or domestic settings.


.: Top Software Articles

1). Track Your MySpace Profile Visitors
I know that everyone who is on MySpace has had the same burning questions that I’ve had. How can I see who has viewed my MySpace profile? Where can I find a MySpace Tracker? Since MySpace has become so popular, so have the MySpace profile stalkers. Could be your friends, neighbors, ex-boyfriends or ex-girlfriends, or even someone you don’t even know.

2). Discover Mozzila FireFox Browser -and How to Install Extensions
Discover Mozilla FireFox Extra Features – Extensions and How To Install Them If you are still not using any other web browser then FireFox (no matter what OS you are using) you are endangering the security of your computer and missing out on a much richer surfing experience. One of Mozilla FireFox browser most powerful feature is the possibility to install extensions.

3). PsP Software Downloads – Review for PsP Blender
PsP software downloads is a very good way to get new software for your psp hand held. You can get psp movies from many different websites. Most of these sites include psp music downloads, psp movie downloads and psp software downloads and of course PsP Games. Many of the databases are different from one site to another. Some sites offer a wide variety of different choices.

4). Tutorial - Enabling IIS 5.1 on Windows XP Pro
Windows XP Home Edition does not support IIS 1. You may need to put your Windows XP Pro CD into the PC. 2. Go to Control Panel, ‘Add Remove Programs’, then ‘Add/Remove Windows Components’. In the Windows Components window, place a check mark beside ‘Internet Information Services (IIS)’, then click next, then click finish. 3. During installation, Windows creates a directory at C:inetpubwwwroot and places a few files there.

5). PsP Software – Review of Software Download Sites
PsP handhelds are one of the newest and most fun ways to play games, watch movies and listen to music. PsP software downloads are just some things that you can do to improve your psp. PsP software downloads are fun and easy. There are many places on the net were one can find psp software downloads. Some sites have you pay per download and sometimes charge up to a couple dollars for each download.

6). What To Do When Windows Fail To Boot
Copyright 2006 Otis Cooper When Windows fails to boot it is normally caused by you installing a program or device and it has caused a conflict with one or more other programs. This will no doubt give you plenty of heartaches if you're not certain which program caused Windows to not boot up. If you recently installed a program or application and know where it was installed,you may be in much better shape as for as correcting the error.

7). SQL Server 2000 Data Types
SQL Server requires that each variable and column in a table should be defined with respect to the type of data it will store. From a bit to a huge image and binary storage types, the allocation is supposed to help the user conform to the data required, and help the engine allocate space and processing speed efficiently. Built-in data types SQL.


Page loaded in 0.169 seconds.