A cursor is an iterator. They are used inside stored procedures to iterate through the result set.
The cursors have the following characteristics
To use a cursor inside a stored procedure we do the following
DECLARE <cursor_name> CURSOR FOR <select_statement>;
Open i.e. initialize the cursor using the Open statement as:
OPEN <cursor-name>;
Retreive records using the FETCH statement
FETCH <cursor_name> INTO <variable-names>;
After every Fetch it is a good idea to check if next row exists. To do so we do:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
This ensures that if there are no more records, the cursor will not attempt to iterate through it and not fail.
Close the cursor once done
CLOSE <cursor-name>;
A stored Procdeure with a cursor for getting all the full names of employees.
DELIMITER $$
CREATE PROCEDURE getFullName ( INOUT fullNameList varchar(4000)
)
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE fullName varchar(100) DEFAULT "";
#Cursor declaration
DEClARE curName
CURSOR FOR
SELECT concat(first_name ,' , ' , last_name) FROM employees LIMIT 10;
#declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
#Open cursor
OPEN curName;
#fetch records
getName: LOOP
FETCH curName INTO fullName;
IF finished = 1 THEN LEAVE getName;
END IF;
SET fullNameList = CONCAT(fullName,";",fullNameList);
END LOOP getName;
CLOSE curName;
END$$
DELIMITER ;
To see the output, we would do:
SET @fullNameList = "";
CALL getFullName(@fullNameList);
SELECT @fullNameList;