sql必知必会
(七)游标
第二十一课 使用游标
21.1 游标
游标是SELECT查询结果集,可以前进或后退行等。
21.2 使用游标
21.2.1 创建游标
DECLARE ordernumbers CURSOR
21.2.2 打开/关闭游标
OPEN cursorname;
CLOSE cursorname;
21.2.3 使用游标数据
FETCH cursorname INTO tmp;
Example
CREATE PROCEDURE processorders()
BEGIN
-- 定义局部变量
DECLARE tmp INT;
DECLARE done BOOLEAN DEFAULT 0;
DECLARE t DECIMAL(8, 2);
-- 定义游标
DECLARE ordernumbers CURSOR
FOR
SELECT order_num FROM orders;
-- 定义continue handler
DECLARE CONTINUE HANDLER
FOR
SQLSTATE '02000' SET done = 1; -- 当没有行后done设置为1
-- 定义表保存结果
CREATE TABLE IF NOT EXISTS ordertotals
(order_num INT,
total DECIMAL(8, 2));
-- 游标操作
OPEN ordernumbers; -- 打开游标
-- 循环读取
REPEAT
FETCH ordernumbers INTO tmp;
CALL ordertotal(tmp, 1, t); -- ordertotal是已定义的存储过程
INSERT INTO ordertotals(order_num, total)
VALUES(tmp, t);
UNTIL done END REPEAT;
CLOSE ordernumbers; -- 关闭游标
END;