• MySQL的游标遍历


    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			
    
    • 1
    • 2
    • 3
    • 4
    • 5

    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;
    
    • 1
    • 2
    • 3
    • 4

    游标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 $$
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
  • 相关阅读:
    【力扣每日一题】2023.9.2 最多可以摧毁的敌人城堡数量
    一文图解爬虫_姊妹篇(spider)
    为指定 java 类生成 PlantUML puml文件工具( v2 )
    Node.js vs. Spring Boot:Hello World 性能对决,谁更快一点?
    调整SGA遇到ORA-00845错误
    2023 RISC-V 中国峰会 演讲幻灯片和视频回放 均已公开
    面试精选-前端
    谈谈 Redis 过期删除策略
    C++项目——云备份-⑤-数据管理模块的设计与实现
    Aruba 胖AP配置-Aruba胖AP默认密码
  • 原文地址:https://blog.csdn.net/qq_39065491/article/details/134418446