IT:AD:SQL Server:HowTo:SQL:Cursors

Cursors/are/just/Iterators, much like any C# GetEnumerator() statement…just a heck of a lot more verbose.

--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

  • /home/skysigal/public_html/data/pages/it/ad/sql_server/howto/sql/cursors.txt
  • Last modified: 2023/11/04 02:28
  • by 127.0.0.1