A cursor in MySQL is used to process the rows returned by a query one row at a time. Cursors are mainly used inside stored procedures and stored functions when we need to perform an operation on each row individually.
- Processes query results row by row.
- Used inside stored programs such as procedures.
- Allows individual rows to be read and processed.
- Uses DECLARE, OPEN, FETCH and CLOSE statements.
Syntax
DECLARE cursor_name CURSOR FORSELECT column1, column2FROM table_name;
Steps to Use a Cursor
A cursor generally follows these four steps:
- DECLARE : Define the cursor and the query.
- OPEN : Open the cursor.
- FETCH : Retrieve rows one at a time.
- CLOSE : Close the cursor.
Example
Consider the following employees table:
| employee_id | employee_name | salary |
|---|---|---|
| 1 | John | 50000 |
| 2 | Emily | 60000 |
| 3 | Michael | 70000 |
Suppose we want to process each employee's salary one by one.
DELIMITER //CREATE PROCEDURE process_employees()BEGINDECLARE done INT DEFAULT 0;DECLARE emp_name VARCHAR(100);DECLARE emp_salary DECIMAL(10,2);DECLARE employee_cursor CURSOR FORSELECT employee_name, salaryFROM employees;DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;OPEN employee_cursor;read_loop: LOOPFETCH employee_cursor INTO emp_name, emp_salary;IF done = 1 THENLEAVE read_loop;END IF;SELECT emp_name, emp_salary;END LOOP;CLOSE employee_cursor;END //DELIMITER ;
Execute the Procedure
CALL process_employees();Output:
| emp_name | emp_salary |
|---|---|
| John | 50000.00 |
| Emily | 60000.00 |
| Michael | 70000.00 |
The cursor reads each employee record one at a time and processes the employee name and salary.