Welcome to our in-depth guide on SQL Cursor Types! In this lesson, we'll explore different types of cursors in SQL, their usage, and practical examples. Let's get started!
Cursors in SQL are a control structure that allows you to manipulate a set of records one at a time. They provide a way to iterate through a result set and perform operations on each row.
Cursors are useful when dealing with complex data manipulation tasks that cannot be achieved using standard SQL statements. They allow for more flexibility in processing data, making them valuable in specific scenarios.
SQL supports two types of cursors:
Implicit Cursors: They are automatically created by the SQL engine when executing a SELECT INTO statement. Implicit cursors are used for a single fetch operation and are not explicitly declared.
Explicit Cursors: These are manually declared cursors that can be opened, closed, and manipulated. Explicit cursors are used for multiple fetch operations.
Here's an example of how to declare an explicit cursor:
DECLARE cursor_name CURSOR FOR SELECT_statement;Replace cursor_name with a unique identifier for your cursor and SELECT_statement with the SQL statement to be executed.
Once a cursor is declared, it needs to be opened to begin processing the result set:
OPEN cursor_name;After the cursor has been used, it should be closed to release resources:
CLOSE cursor_name;To fetch data from a cursor, use the FETCH statement:
FETCH NEXT n FROM cursor_name;Replace n with the number of rows to fetch (default is 1).
Let's create a simple example using an explicit cursor to update the salary of employees in a database.
-- Declare the cursor
DECLARE emp_cursor CURSOR FOR
SELECT employee_id, salary FROM employees WHERE salary < 50000;
-- Open the cursor
OPEN emp_cursor;
-- Define a variable to hold the fetched data
DECLARE @employee_id INT, @salary INT;
-- Loop through the cursor and update the salary of each employee
DECLARE CONTINUE HANDLER FOR NOT FOUND EXIT;
REPEAT
-- Fetch the next row
FETCH NEXT FROM emp_cursor INTO @employee_id, @salary;
-- Update the salary
UPDATE employees SET salary = @salary * 1.1 WHERE employee_id = @employee_id;
UNTIL NOT FOUND;
-- Close the cursor
CLOSE emp_cursor;This example declares an explicit cursor that fetches employees with a salary less than 50,000. It then loops through the cursor, updating the salary of each employee by 10%.
What is the purpose of SQL Cursors?
What are the two types of SQL Cursors?