深入理解MySQL中的游标操作
最编程
2024-08-05 08:12:15
...
-- 使用游标创建一个存储过程,统计年龄大于19的记录的数量
delimiter //
create procedure p2()
begin
-- 创建 用于接收游标值的变量
declare id,age,total int;
-- 注意 接收游标值为中文时 需要 给变量 指定 字符集为utf8
declare name,sex varchar(20) character set utf8;
-- 游标结束的标志
declare done int default 0;
-- 声明游标
declare cur cursor for select stuId,stuName,stuSex,stuAge from student where stuAge > 19;
-- 指定游标循环结束时的返回值
declare continue handler for not found set done =1;
-- 打开游标
open cur;
-- 初始化 变量
set total = 0;
-- loop 循环
xxx:loop
-- 根据游标当前指向的一条数据
fetch cur into id,name,sex,age;
-- 当 游标的返回值为 1 时 退出 loop循环
if done = 1 then
leave xxx;
end if;
set total = total + 1; -- 累计
end loop;
close cur; -- 关闭游标
select total; -- 输出 累计的结果
end //
delimiter ;
上一篇: 理解并掌握MySQL游标:定义与应用
下一篇: MySQL新手指南:掌握游标和事务操作