A few days ago a project that I was working on required me to loop through a result set from a select statement. Most examples used database cursors. However, I came across an old article that shows an alternative method for doing this.
Let’s pretend that we had a scenario that we want to loop over the rows in this table and print the fishinglicense. We can do this without using a database cursor. Here is some code to ponder on
DECLARE @fishingLicense VARCHAR(50)
DECLARE @id INT
DECLARE @rowNum INT
DECLARE @maxrows INT
SELECT TOP 1 @id = DuckstickUserID,
@fishingLicense = FishingLicense
FROM DuckstickUser
SELECT @maxRows = COUNT(*)
FROM DuckstickUser
SET @rowNum = 0
-- Loop until last row is reached
WHILE @rowNum < @maxRows
BEGIN
SET @rowNum = @rowNum + 1
-- this is where you can now do something to the record
PRINT( 'Processing user: ' + @fishingLicense )
-- now we grab the next row making sure the ID of the next row
-- is greater than previous row
SELECT TOP 1 @id = DuckstickUserID,
@fishingLicense = FishingLicense
FROM duckstickuser
WHERE DuckstickUserID > @id
END
This can be very useful when you need to iterate items in a table.