CS 377 [Spring 2016] - Ho
Example: Cursor
DELIMITER //!
CREATE PROCEDURE cursor1()!
BEGIN !
DECLARE finished INTEGER DEFAULT 0;!
DECLARE fname1 CHAR(20) DEFAULT "";!
DECLARE lname1 CHAR(20) DEFAULT "";!
DECLARE nameList CHAR(100) DEFAULT "";!
-- 1. Declare cursor for employee !
DECLARE emp_cursor CURSOR FOR SELECT fname, lname FROM employee WHERE salary > 40000;!
-- 2. Declare NOT FOUND handler!
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;!
-- 3. Open the cursor!
OPEN emp_cursor;!
L: LOOP !
-- 4. Fetch next tuple!
FETCH emp_cursor INTO fname1, lname1;!
-- Handler will set finished = 1 if cursor is empty!
IF finished = 1 THEN !
LEAVE L;!
END IF;!
-- build emp list!
SET nameList = CONCAT( nameList, fname1, ' ', lname1, ';' );!
END LOOP ;!
-- 5. Close cursor when done !
CLOSE emp_cursor;!
SELECT nameList ;!
END // !
DELIMITER ;