Monday, January 9, 2012

SQL Server : Iterating/Traversing rows / results in T-SQL



You may used to iterate records on your application code using from recordset object and looping structure. Well, here are the simple codes which do almost the same thing in SQL Server.


-----------------------------------------------------


DECLARE @mycursor CURSOR
DECLARE @current_row bigint


SET @mycur = CURSOR
FOR
select top 100 id_number from mytablename (however SQL statement that you prefer)


OPEN @mycursor


FETCH NEXT FROM @mycur INTO @current_row


WHILE @@FETCH_STATUS = 0
BEGIN
            --put any processes that you need to do here
FETCH NEXT FROM @mycur INTO @current_row --move to next row.
END


CLOSE @current_row
DEALLOCATE @mycur

No comments:

Post a Comment