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.