Skip to content
 

SQL Server For Each Row Next

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 CustomerID)
	,*
INTO #Customers
FROM SalesLT.Customer

DECLARE @MaxRownum int
SET @MaxRownum = (SELECT MAX(RowNum) FROM #Customers)

DECLARE @Iter int
SET @Iter = (SELECT MIN(RowNum) FROM #Customers)

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

	-- run your operation here

	SET @Iter = @Iter + 1
END

DROP TABLE #Customers

Once again, take heed, even though this is how to loop, I encourage set-based operations whenever possible.

Related Posts:

Ask a question or post a comment