Sqlserver-dba.com

Performance Myth : Replacing a CURSOR with a WHILE LOOP and think you are not processing with a row

Switching from using a CURSOR to a WHILE loop will mean they are not processing by a row. This is not true. The following examples illustrates this myth. Both examples are processing row by row :
Example 1 - CURSOR

create table #mytemp
(ID INT ,
avalue VARCHAR(100),
status INT
)
INSERT INTO #mytemp (ID,avalue,status) VALUES(1,'Mick Jagger',0)
INSERT INTO #mytemp (ID,avalue,status) VALUES(2,'Keith Richards',0)
INSERT INTO #mytemp (ID,avalue,status) VALUES(3,'Ron Wood',0)
declare @cnt INT,@tmpINT INT
SET @cnt = 1
DECLARE my_cursor CURSOR FOR
SELECT ID FROM #mytemp
OPEN my_cursor
FETCH NEXT FROM my_cursor
INTO @tmpINT
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @cnt
UPDATE #mytemp SET status = 1 WHERE ID = @cnt
SET @cnt = @cnt + 1
FETCH NEXT FROM my_cursor
INTO @tmpINT;
END
CLOSE my_cursor;
DEALLOCATE my_cursor;

Example 2 - WHILE loop

create table #mytemp
(ID INT ,
avalue VARCHAR(100),
status INT
)
INSERT INTO #mytemp (ID,avalue,status) VALUES(1,'Mick Jagger',0)
INSERT INTO #mytemp (ID,avalue,status) VALUES(2,'Keith Richards',0)
INSERT INTO #mytemp (ID,avalue,status) VALUES(3,'Ron Wood',0)
declare @cnt INT
SET @cnt = 1
WHILE (SELECT COUNT(*) FROM #mytemp WHERE status = 0) 0
BEGIN
UPDATE #mytemp SET status = 1 WHERE ID = @cnt
SET @cnt = @cnt + 1

END
SELECT * FROM #mytemp
DROP TABLE #mytemp

Source:Jack Vamvas (http://www.sqlserver-dba.com)
Author: Jack Vamvas (http://www.sqlserver-dba.com)

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact