A cursor allows you to iterate over the rows of a result set one at a time inside a stored procedure. This is useful when you need to perform row-by-row processing that cannot be expressed as a set-based SQL operation.
Cursor Lifecycle
- DECLARE the cursor with a SELECT statement
- DECLARE CONTINUE HANDLER FOR NOT FOUND to detect end of rows
- OPEN the cursor to execute the SELECT
- FETCH rows one at a time into variables
- CLOSE the cursor when done
Performance Note
Cursor-based row-by-row processing is significantly slower than set-based SQL. Use cursors only when set-based logic is genuinely insufficient. Often a JOIN or subquery can replace a cursor entirely.