MySQL的游标遍历
1.数据准备
测试表 tb_student 数据结构如下:
Field Type Null Key Default Extra
name varchar(10) YES
grade int(11) YES
class int(11) YES
birthday date YES
2. 存储过程
两个游标cur_stud1 和 cur_stud2
重点说明:
(1)游标结束处理标志,一个程序段中只能有一个。
#游标结束标志,必须在游标声明后声明!!!
declare continue handler for not found set done = 1 ;
(2)游标遍历,使用loop循环遍历最简单明了。用while循环,遍历的记录处理需要再次判断一下,否则最后一条记录重复两次。
# 避免最后一条记录select两次
if done = 0 then
select concat(v_name,':',date_format(v_date,'%Y%m%d'));
end if;
游标close之后,还可以open ,再fetch 数据。
(3)示例程序
delimiter $$
CREATE PROCEDURE pro_test_fetch_cursor()
begin
declare done int default 0 ;
declare v_name varchar(10);
declare v_date date;
declare cur_stud1 cursor for select t.name ,t.birthday from tb_student t where t.grade >= 70 and t.grade < 80 order by t.grade desc limit 5;
declare cur_stud2 cursor for select t.name ,t.birthday from tb_student t where t.grade >= 80 and t.grade < 90 order by t.grade desc limit 5;
#游标结束标志,必须在游标声明后声明!!!
declare continue handler for not found set done = 1 ;
#使用游标前打开游标
open cur_stud1 ;
#循环的标签名称,要和end loop 对应。
#使用loop循环访问游标
getloop : loop
fetch cur_stud1 into v_name ,v_date;
if done = 1
then leave getloop ;
end if ;
select concat(v_name,':',date_format(v_date,'%Y%m%d'));
end loop getloop;
close cur_stud1 ;
#使用while循环访问游标 ,由于会fetch后激活done设置,所以最后一条记录会fetch两次,循环中用if再次判断一下。
set done = 0;
open cur_stud2;
while done <> 1 do
fetch cur_stud2 into v_name ,v_date;
# 避免最后一条记录select两次
if done = 0 then
select concat(v_name,':',date_format(v_date,'%Y%m%d'));
end if;
end while;
close cur_stud2 ;
end $$