473,385 Members | 1,856 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

To Use a Cursor or to Not Use a Cursor

I need to loop through a set of records to build a string. I can do
this without using a cursor by inserting the records into a temporary
table with an identity column. Count the number of records in the
temporary table and loop though the table selecting the values and
building the string where the identity column = the loop number.

Is this more or less efficient than just using a cursor? If so why is
it more or less efficient?

Please explain in detail

Thank You,
Jim Lewis
Jul 20 '05 #1
6 15671
j_*********@hotmail.com (Jim Lewis) wrote in message news:<78*************************@posting.google.c om>...
I need to loop through a set of records to build a string. I can do
this without using a cursor by inserting the records into a temporary
table with an identity column. Count the number of records in the
temporary table and loop though the table selecting the values and
building the string where the identity column = the loop number.

Is this more or less efficient than just using a cursor? If so why is
it more or less efficient?

Please explain in detail

Thank You,
Jim Lewis


Without sample tables, data and code, it's not possible to say for
sure, however, as a general rule, a cursor operation is slower than
other approaches. You should be able to test both operations using
Query Analyzer, with Show Execution Plan turned on. The plan will show
what percentage of the batch was taken up by each operation, so if a
loop is 25% and a cursor is 75%, then the loop is more efficient.

If you do this, you need to ensure that caching isn't distorting your
results, so you should execute DBCC FREEPROCCACHE and DBCC
DROPCLEANBUFFERS before testing each option. Something like this:

DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE
exec dbo.ProcUsingLoop

DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE
exec dbo.ProcUsingCursor

Simon
Jul 20 '05 #2
Jim

In most cases if you can use another method rather than using a cursor
with SQL Server use it. Cursors in SQL Server use a lot of resources
and are in nearly all cases are slower than the alternatives.

I did have a very good paper on why not to use cursors, but
unfortunately I can't find it. A good way to see the difference is to
write it both ways and use QA to see the execution plan and profiler
to capture what it actually does.

Good luck

John
Jul 20 '05 #3
I started writing code to determine which was the more efficient
approach and I encountered something interesting

CREATE TABLE TestLoop (
TestLoopID int IDENTITY (1, 1) NOT NULL ,
FirstName varchar(50) NULL)

INSERT INTO TestLoop (FirstName) VALUES ('Tom')
INSERT INTO TestLoop (FirstName) VALUES ('Dick')
INSERT INTO TestLoop (FirstName) VALUES ('Harry')

DECLARE @OutPut as Vachar(8000)
SET @OutPut = ''

SELECT @OutPut = @OutPut + FirstName FROM TestLoop

--Output Tom, Dick, Harry,

I do not know that T-SQL would flatten all the values into the string.
There is no need for looping at all! How and why does SQL Server do
this?
Jul 20 '05 #4
<snip>
SELECT @OutPut = @OutPut + FirstName FROM TestLoop

--Output Tom, Dick, Harry,

I do not know that T-SQL would flatten all the values into the string.
There is no need for looping at all! How and why does SQL Server do
this?


Because this proprietary syntax is allowed. However, there are several
disadvantages/problems with it. For example, you have no control over
the order in which the strings are concatenated. Often it is a
requirement to concatenate the strings in sorted order.

Because of these problems IMO it is better to use a solution that is
reliable. A solution that will also still work when you apply a service
pack or when you port the code to a new SQL-Server version. In this case
this could be by using a loop or a cursor.

Hope this helps,
Gert-Jan
Jul 20 '05 #5
Jim Lewis (j_*********@hotmail.com) writes:
I started writing code to determine which was the more efficient
approach and I encountered something interesting

CREATE TABLE TestLoop (
TestLoopID int IDENTITY (1, 1) NOT NULL ,
FirstName varchar(50) NULL)

INSERT INTO TestLoop (FirstName) VALUES ('Tom')
INSERT INTO TestLoop (FirstName) VALUES ('Dick')
INSERT INTO TestLoop (FirstName) VALUES ('Harry')

DECLARE @OutPut as Vachar(8000)
SET @OutPut = ''

SELECT @OutPut = @OutPut + FirstName FROM TestLoop

--Output Tom, Dick, Harry,

I do not know that T-SQL would flatten all the values into the string.
There is no need for looping at all! How and why does SQL Server do
this?


By pure chance, it seems. I tried to explain this in my previous
article. You can to do this, but the result of this kind of statement
is not defined. So for robust code, yes, you need to loop.

See also http://support.microsoft.com/default.aspx?scid=287515, and
pay particular attention to the first sentence in the CAUSE section.

--
Erland Sommarskog, SQL Server MVP, so****@algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #6
j_*********@hotmail.com (Jim Lewis) wrote in
news:78**************************@posting.google.c om:
I started writing code to determine which was the more efficient
approach and I encountered something interesting

CREATE TABLE TestLoop (
TestLoopID int IDENTITY (1, 1) NOT NULL ,
FirstName varchar(50) NULL)

INSERT INTO TestLoop (FirstName) VALUES ('Tom')
INSERT INTO TestLoop (FirstName) VALUES ('Dick')
INSERT INTO TestLoop (FirstName) VALUES ('Harry')

DECLARE @OutPut as Vachar(8000)
SET @OutPut = ''

SELECT @OutPut = @OutPut + FirstName FROM TestLoop

From what you've written so far, I don't think ANYTHING would be *output*.
If you added

SELECT @OutPut

as a command after the above, I would expect this result

TomDickHarry
--Output Tom, Dick, Harry,

I do not know that T-SQL would flatten all the values into the string.
There is no need for looping at all! How and why does SQL Server do
this?


Next, the truth is that the result is undefined because there is no
telling what order the optimizer will choose to return the results in.
E.g., if you happened to have created an index on FirstName, the optimizer
might very well decide that the index was the quickest way to get the
field values - and since you did not specify an ORDER BY Clause, you might
well get this output:

DickHarryTom

However, in controlled situations, this sort of shenanigans will generally
function as required. A great many cursors can be eliminated with
cleverness of this sort - but don't tell Mama.

--
Ross Presser -- rpresser AT imtek DOT com
"... VB is essentially the modern equivalent of vulgar Latin in 13th
Centurary Europe. Understand it, and you can travel to places you never
heard of and still understand some people." -- Alex K. Angelopoulos
Jul 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Csaba2000 | last post by:
I have set onmousedown to change the cursor, but this setting is ignored (IE 5.5; NN 6.1 on Win 2K Pro) until the mouse is either moved or the mouse button is released. On Opera 7.01, the setting...
5
by: Vlad Simionescu | last post by:
Hello I'm trying to let my Windows Form application perform a lengthy operation while displaying a progress bar in a modal dialog window; the dialog has a cancel button. The dialog is displayed...
2
by: dave | last post by:
In my form Ive got a SaveData() routine that saves changes to a DB. When I encounter an exception in the save operations, I am having trouble chaning the cursor back to the default cursor, it just...
5
by: Lespaul36 | last post by:
I have a mdi app. I need to change the cursor when I click on certain button on a form that I made into a toolbar. I tried to use cursor.current. But the cursor won't show. if I change the form...
10
by: Just Me | last post by:
Does Me.Cursor.Current=Cursors.WaitCursor set the current property of Me.Cursor to Cursors.WaitCursor And Me.Cursor.Current=Cursors.Default set the Me.Current property to something (default)...
2
by: Alex | last post by:
In the code below, clicking on the button ButtonChangeCursor changes the form's cursor to a WaitCursor. Clicking the button ButtonRestoreCursor changes the form's cursor back to its original...
2
by: Jim Frazer | last post by:
Hi, I'm working on an application in C# that will allow the user to create simple CAD drawings on a CEPC system. I would like to be able to change the cursor shape depending on the drawing mode...
7
by: Academic | last post by:
What are the different effects of the following two statements: C1.Cursor = Cursors.WaitCursor C1.Cursor.Current = Cursors.WaitCursor I believe the first replaces the entire C1.Cursor...
0
debasisdas
by: debasisdas | last post by:
RESTRICTIONS ON CURSOR VARIABLES ================================= Currently, cursor variables are subject to the following restrictions: Cannot declare cursor variables in a package spec. ...
4
by: mike | last post by:
I have the opportunity to rescue a project that uses a mouse to sense the relative position of a machine. The hardware is built...just needs to be programmed. Stop snickering!!! I didn't do it...I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.