SQL Tip #11 – Loop through all records in a Table using WHILE

In order to iterate through the all the records in a table without cursor following approach could be a help. Please replace SampleTable and SampleTableID with your preferred Table info.

IF OBJECT_ID('tempdb..#memTable') IS NOT NULL
BEGIN
	DROP TABLE #memTable
END


SELECT ROW_NUMBER() OVER (ORDER BY [SampleTableID] ASC) 
       AS RowNo
       ,*
INTO #memTable
FROM [dbo].SampleTable 



DECLARE @ctr INT = 1
DECLARE @recordCount INT = (SELECT COUNT(1) FROM #memTable)
             

WHILE (@ctr <=@recordCount)
BEGIN

       SELECT
          *
       FROM #memTable WHERE RowNo = @ctr

        SET @ctr = @ctr + 1
END