Wednesday, 9 February 2011

T-SQL: Looping Without Cursors or Temporary Tables

Today, I found a neat way of looping through records in a table without running the risk of hogging memory up with cursor or temporary tables. This technique involves querying against the recordset one record at a time. @@ROWCOUNT is used to determine when the end of recordset has been reached.

Example:

USE AdventureWorks
DECLARE @loopid  INT, @loopval VARCHAR(255)

SELECT TOP 1 @loopid = AddressID, @loopval = AddressLine1
FROM   Person.Address
WHERE  City = 'Seattle'

WHILE @@ROWCOUNT > 0
  BEGIN
      PRINT @loopval -- do stuff here
      SELECT TOP 1 @loopid = AddressID, @loopval = AddressLine1
      FROM   Person.Address
      WHERE  City = 'Seattle'
             AND AddressID > @loopid
  END 

Because this techinque involves querying the table multiple times, it might not be a good idea to use it against a huge recordset, or one without a valid index.