游标使用的整个过程:
1.创建游标
DECLARE calc_bonus CURSOR FOR SELECT id, salary, commission FROM employees;
2.打开游标
OPEN calc_bonus;
3.使用游标
FETCH calc_bonus INTO re_id, re_salary, re_comm;
4.关闭游标
CLOSE calc_bonus;
==================================================================================================
以前面提到的计算奖金为实例,给出一个存储过程,在其中使用游标:
DELIMITER //
CREATE PROCEDURE calculate_bonus()
BEGIN
DECLARE emp_id INT;
DECLARE sal DECIMAL(8, 2);
DECLARE comm DECIMAL(3, 2);
DECLARE done INT;
DECLARE calc_bonus CURSOR FOR SELECT id, salary, commission FROM employees;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN calc_bonus;
BEGIN_calc: LOOP
FETCH calc_bonus INTO emp_id, sal, comm;
IF done THEN
LEAVE begin_calc;
IF sal > 60000 THEN
IF comm > 0.05 THEM
UPDATE employees SET bonus = sal * comm WHERE id = emp_id;
ELSEIF comm <= 0.05 THEN
UPDATE employees SET bonus = sal * 0.03 WHERE id = emp_id;
END IF;
ELSE
UPDATE employees SET bonus = sal * 0.07 WHERE id = emp_id;
END IF;
END LOOP begin_calc;
CLOSE calc_bonus;
END//
DELIMITER ;
原文地址:http://my.oschina.net/u/582827/blog/313512