CURSOR
CURSOR in SQL is a database object used to retrieve rows from a result set one at a time. Instead of fetching all records at once, the CURSOR allows for managing and processing each row individually, sequentially, providing greater control over the query results. They are usually used for complex calculations, row-based operations or where data needs to be manipulated on a row by row basis.
Example
Output
Explanation
In the above example, a cursor named db_cursor
is declared and associated with a SELECT statement that fetches the names from the requirements
table. The cursor is then opened, and a WHILE loop is used to iterate through the rows returned by the query. For each iteration, FETCH NEXT is called to move the cursor to the next row. When all rows have been processed, the cursor is closed and deallocated.
Example
Output
Explanation
In the provided example, a cursor cur
is declared for a SELECT
query which gets all data from the employees
table. FETCH NEXT FROM cur;
is used to fetch the next row of from the result set of the cursor cur
. CLOSE cur;
is used to close the cursor once all rows have been fetched and processed. The output simulates a scenario where the employees
table has at least one row of data, and is designed to show that the cursor fetches this data successfully.
Example
Output
Explanation
In this example, a CURSOR named cur
is declared and a SELECT query is provided as source of the cursor. The cursor is then opened and a column (name) from SQL Server’s built-in databases
data is fetched row by row into the variable @Name
until there are no more rows left to fetch. For each fetch, the database name is printed. After fetching all rows from the cursor, the cursor is closed and deallocated.
Example
Output
Explanation
The aforementioned SQL declares a CURSOR
cur_employees that retrieves first and last names from the employees table. The LOOP
fetches each record from the CURSOR
and outputs the ‘first_name’ and ‘last_name’ before moving to the next record. If no more records are available, it stops fetching and closes the cursor.