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
This is only a preview. Your comment has not yet been posted.
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.
Posted by: |