Iterate over rows in a stored procedure?
To iterate row-by-row over a query result set inside a stored procedure, use a CURSOR:
### Cursor Lifecycle Steps:
DECLARE: Define the cursor and query.OPEN: Initialize the cursor result set.FETCH: Retrieve the next row into local variables.CLOSE: Free cursor memory resources.
DELIMITER //
CREATE PROCEDURE ProcessCustomers()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE cust_id INT;
DECLARE cur CURSOR FOR SELECT id FROM Customers;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO cust_id;
IF done THEN
LEAVE read_loop;
END IF;
-- Process each customer ID here
END LOOP;
CLOSE cur;
END //
DELIMITER ;
*Performance Warning:* Databases are optimized for set-based operations. Cursors execute row-by-row ($O(n)$ procedural execution) and should only be used when set-based SQL logic is impossible.