Brian's Blog

items I see across my tribes

TSQL: Looping through a Table

November 16
by briancarter 16. November 2010 08:50

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. 

Categories: Development


 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.