BEGIN DECLARE idCount int DEFAULT 0;-- 定义查询的id count DECLARE nameCount int DEFAULT 0;-- 统计相同名字合计 DECLARE openerId int DEFAULT 0; DECLARE openerName VARCHAR(255); -- 遍历数据结束标志 DECLARE done INT DEFAULT FALSE; -- 定义游标 DECLARE cur CURSOR FOR select count(*) count,opener FROM qf_invoice where (`status` >10 or `status` =1) GROUP BY opener; -- 将结束标志绑定到游标 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; -- 打开游标 OPEN cur; -- 开始循环 read_loop: LOOP -- 提取游标里的数据,这里只有一个,多个的话也一样; FETCH cur INTO nameCount,openerName; SELECT nameCount,openerName; -- 声明结束的时候 IF done THEN SELECT 'done'; LEAVE read_loop; END IF; -- 业务逻辑 SELECT id,COUNT(id) into openerId,idCount from qf_merchant_invoice where `status` = 1 and opener = openerName; if(idCount !=0) THEN -- 查询结果为null时游标会主动退出 update qf_merchant_invoice SET invoice_number = invoice_number + nameCount where id = openerId; ELSE INSERT into qf_merchant_invoice(opener,invoice_number,create_time,STATUS) VALUES(openerName,nameCount,NOW(),1); end if; END LOOP; -- 关闭游标 CLOSE cur;END
有一点:有时候使用游标要使用别名,不然会造成游标结果和sql查询不一致;
加上别名:
不加别名:
数据库直接查询结果