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:
RowNum = ROW_NUMBER() OVER(ORDER BY CustomerID)
DECLARE @MaxRownum INT
SET @MaxRownum = (SELECT MAX(RowNum) FROM #Customers)
DECLARE @Iter INT
SET @Iter = (SELECT MIN(RowNum) FROM #Customers)
WHILE @Iter <= @MaxRownum
WHERE RowNum = @Iter
-- run your operation here
SET @Iter = @Iter + 1
DROP TABLE #Customers
Once again, take heed, even though this is how to loop, I encourage set-based operations whenever possible.