Cursors are used by database programmers to process individual rows returned by database system queries. Cursors enable manipulation of whole result sets at once—a capability that most procedural programming languages lack. In this scenario, a cursor enables the rows in a result-set to be processed sequentially.
This section introduces the ways the SQL:2003 standard defines how to use cursors in applications in embedded SQL. Not all application bindings for relational database systems adhere to that standard, and some (such as CLI or JDBC) use a different interface.
A programmer makes a cursor known to the DBMS by using a
DECLARE ... CURSOR statement and assigning the cursor a (compulsory) name:DECLARE cursor_name CURSOR FOR SELECT ... FROM ...
Before code can access the data, it must open the cursor with the
OPEN statement. Directly following a successful opening, the cursor is positioned before the first row in the result set.OPEN cursor_name
Programs position cursors on a specific row in the result set with the
FETCH statement. A fetch operation transfers the data of the row into the application.FETCH cursor_name INTO ...
Once an application has processed all available rows or the fetch operation is to be positioned on a non-existing row (compare scrollable cursors below), the DBMS returns a SQLSTATE '02000' (usually accompanied by an SQLCODE +100) to indicate the end of the result set.
The final step involves closing the cursor using the
CLOSE statement:CLOSE cursor_name
Example:
DECLARE @fName varchar(50), @lName varchar(50) DECLARE cursorName CURSOR -- Declare cursor LOCAL SCROLL STATIC FOR Select firstName, lastName FROM myTable OPEN cursorName -- open the cursor FETCH NEXT FROM cursorName INTO @fName, @lName PRINT @fName + ' ' + @lName -- print the name WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM cursorName INTO @fName, @lName PRINT @fName + ' ' + @lName -- print the name END CLOSE cursorName -- close the cursor DEALLOCATE cursorName -- Deallocate the cursor