Brian's Blog

items I see across my tribes

SQL Server For Each Row Next

July 22
by briancarter 22. July 2010 07:00

It is difficult for me to write this particular article and I’ll tell you why. If you don’t care then just skip down to the example, but here goes anyway. It is very rare that you should have to perform looping in SQL. There are certain situations that do require it, and they are mostly back-end or maintenance related.

Ok, now that I got that off my chest, here you go. In order to perform an execution which iterates performing a “for each row”, this is the easiest way for me:

SELECT RowNum = Row_number() OVER(ORDER BY AttributeID), *
INTO   #Attributes
FROM   Attribute

DECLARE @MaxRownum INT
SET @MaxRownum = (SELECT MAX(RowNum)
                  FROM   #Attributes)

DECLARE @Iter INT
SET @Iter = (SELECT MIN(RowNum)
             FROM   #Attributes)

WHILE @Iter <= @MaxRownum
  BEGIN
      SELECT *
      FROM   #Attributes
      WHERE  RowNum = @Iter

      -- run your operation here
      SET @Iter = @Iter + 1
  END

DROP TABLE #Attributes 

Once again, take heed, even though this is how to loop, I encourage set-based operations whenever possible.  This does save you from deploying a console app when a simple iteration is needed.

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.