DELIMITER $$
DROP PROCEDURE IF EXISTS `test2`.`sp_cur_demo`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_cur_demo`()
BEGIN
-- Variants declare
DECLARE i INT DEFAULT 0;
DECLARE cnt INT DEFAULT 0;
DECLARE a,b INT;
DECLARE c CHAR(1);
-- Define cursor
-- Notice:Cursor's declaration must be after ordinary variant.
DECLARE cur1 CURSOR FOR SELECT a1 from t1;
DECLARE cur2 CURSOR FOR SELECT a2 from t1;
DECLARE cur3 CURSOR FOR SELECT a3 from t1;
-- Fetch total number of the table.
SELECT count(1) FROM t1 INTO cnt;
DROP TABLE tmp;
-- Create a temporary table to store the results.
CREATE TEMPORARY TABLE IF NOT EXISTS tmp(cur_c1 int, cur_c2 int,cur_c3 char(1));
OPEN cur1;
OPEN cur2;
OPEN cur3;
-- Begin fetch data into a new temporary table.
WHILE i < cnt DO
FETCH cur1 INTO a;
FETCH cur2 INTO b;
FETCH cur3 INTO c;
INSERT INTO tmp SELECT a,b,c;
SET i = i + 1;
END WHILE;
CLOSE cur1;
CLOSE cur2;
CLOSE cur3;
END$$
DELIMITER ;
|