IT:AD:SQL Server:HowTo:SQL:Cursors
Summary
Cursors/are/just/Iterators, much like any C# GetEnumerator() statement…just a heck of a lot more verbose.
Process
--Declare vars needed DECLARE @ID int, @Amount money, @Sum Money; -- Declare the Iterator: DECLARE db_cursor CURSOR FOR SELECT id, amount FROM Invoices WHERE ... -- Open the cursor, to close it at the end OPEN db_cursor -- Fetch the first results: FETCH NEXT FROM db_cursor INTO @id, @amount -- Conditional WHILE @@FETCH_STATUS = 0 BEGIN -- Operate on first results, and subsequent: @Sum = @Sum + Amount -- Get next row (which will maybe set @@FETCH_STATUS to FETCH NEXT db_cursor INTO @id, @amount END -- Close and release the cursor CLOSE db_cursor -- Remember to deallocate it DEALLOCATE db_cursor