Wednesday, March 28, 2012

How do I loop through the records in a temporary table

How do I loop through the records in a temporary table?
ThanksHi Tim
Processing rows is usually less efficent than using set based commands on
your data set, therefore if you can use a set based solution is should be
better. You can use a CURSOR on a temporary table for example:
SELECT LastName, FirstName
INTO #Employees
FROM Northwind.dbo.Employees
WHERE LastName like 'B%'
DECLARE @.LastName [nvarchar] (20) ,
@.FirstName [nvarchar] (10)
DECLARE Employee_Cursor CURSOR FOR
SELECT LastName, FirstName
FROM #Employees
OPEN Employee_Cursor
FETCH NEXT FROM Employee_Cursor INTO @.LastName, @.FirstName
WHILE @.@.FETCH_STATUS = 0
BEGIN
PRINT @.FirstName + N' ' + @.LastName
FETCH NEXT FROM Employee_Cursor INTO @.LastName, @.FirstName
END
CLOSE Employee_Cursor
DEALLOCATE Employee_Cursor
DROP TABLE #Employees
Check out information on DECLARING/OPENING/CLOSING/DEALLOCATING and FETCHING
from cursors in Books Online
John
"Tim Kelley" wrote:
> How do I loop through the records in a temporary table?
> Thanks
>
>

No comments:

Post a Comment