Using SQL to loop through a result set

Found this code sample recently on how to loop through a result set without using a cursor and therefore reducing any locking problems.


DECLARE @NextID INT
SELECT @NextID = MIN(EmployeeID) FROM Employees
WHILE @NextID IS NOT NULL
BEGIN
SELECT EmployeeID, FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = @NextID
SELECT @NextID = MIN(EmployeeID) FROM Employees WHERE EmployeeID > @NextID
END

The code is incomplete.  I imagine using a SELECT INTO statement to insert the records into a temporary table would be useful.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s