MySQL游标详解

1、游标的概述和理解

游标也叫光标,SQL语句查询出来是一个结果集,但是不能像指针一样定位到每一条记录,游标可以对查询出来的结果集中每一条记录进行定位处理select一次性得到很多内容,但是想对这些内容进行加工(操作),操作完显示在屏幕上。
游标充当指针的作用,操作游标来对数据进行操作、游标一般用在存储过程中

案例理解:
declare cursor_example cursor for select * form user where name like '李%';
定义了一个游标 cursor_example,把select的结果集放到cursor_example里面,游标cursor_example就是一个容器或者一个内存块

2、使用游标的步骤

游标一般有四个步骤:

  • 声明定义游标
  • 打开游标
  • 使用游标
  • 关闭游标

2.1、声明游标

在MySQL用declare关键字声明,语法如下:

declare 游标名 cursor for select 语句;

比如下面的声明游标:

declare cursor_name cursor for select * from user where name like '%阳%';

2.2 打开游标

声明好了游标,在使用前需要打开游标,打开游标时会把select查询的集合送到游标工作区,为后面逐条读取数据准备。

open 游标名;

2.3 使用游标

语法:

fetch 游标名 into 变量名....

fetch是一行一行的获取游标里的内容的,如果游标读取的数据有多列,得需要into 多个变量中。

简单看一个案例:

delimiter $
create procedure girls.demo7()
begin
    declare id int default null;
    declare id2 varchar(20) default null;
    declare cursor_test cursor for select * from user;
    open cursor_test;
    fetch cursor_test into id,id2;
    select id,id2;
    close cursor_test;
end $
delimiter ;

call demo7();


这里只是显示一行数据,实际上不止一条数据的。为啥呢,因为fetch每次都是读取cursor_test的第一行(指针指向的第一行

2.4 关闭游标

游标是占用资源的,需要关闭的,关闭就无法再获取结果数据集了,需要重新打开。语法如下:

close 游标名;

3、案例

declare continue handler for not found set yy = 1; 判断循环是否结束,游标到最后一行数据的依据

drop procedure demo8;
delimiter $
create procedure girls.demo8(IN input_salary float,OUT cv_name varchar(20))
begin
    declare c_name varchar(20) default null;
    declare v_name varchar(100) default '';
    declare yy int default 0;
    declare cursor_name cursor for select name from employees where salary <= input_salary;
    declare continue handler for not found set yy = 1;
    open cursor_name;
    repeat
        fetch cursor_name into c_name;
        if !yy then
            set c_name = concat(c_name,',');
            set v_name = concat(v_name,c_name);
        end if;
        until  yy
    end repeat;
    set cv_name = v_name;
    close cursor_name;
end $
delimiter ;

select name from employees where salary <=8000;

select concat(null,'lisi'); # 为null
select concat('','lisi'); # 为lisi
call demo8(8000,@cv_name);
select @cv_name;

使用FETCH语句获取游标数据最后一行重复,进入循环对标志yy进行判断是否为1。

参看学习:
1、深入学习MySQL游标
2、使用FETCH语句获取游标数据最后一行重复
3、MySQL 游标详解

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值