Implementing a loop using a cursor in SQL

As far as I’m aware, there are two ways of creating a loop. One is with the use of a cursor, and the other is with a WHILE loop.

A while loop is useful if you have a start value and an end value. But, if you have a set of record you wish to iterate over, then a cursor is the way to go.

The following is a good template for using a cursor to loop through data.

DECLARE @Code varchar(50)

DECLARE my_cursor CURSOR FAST_FORWARD FOR
SELECT
Code
FROM
MyTable

OPEN my_cursor
FETCH NEXT FROM my_cursor INTO @Code
WHILE @@FETCH_STATUS = 0
BEGIN

-- Do Stuff

FETCH NEXT FROM my_cursor INTO @Code

END

CLOSE my_cursor
DEALLOCATE my_cursor
Subscribe

0 comments