mysql-游标

一、介绍

  有时需要在检索出来的行中前进或后退一行或多行,这就是使用游标的原因。游标(cursor)是一个存储在MySQL服务器上的数据查询,它不是一条select语句,而是被该语句检索出来的结果集。在存储了游标之后,应用程序可以根据需要滚动或浏览其中的数据。

  游标只能用于函数和存储过程

二、使用游标

  1、在能够使用游标前,必须声明(定义)它,这个过程实际上没有检索数据,它只是定义要使用的select语句。

  2、一旦声明后必须打开游标以供使用,这个过程用前面定义的select语句把数据实际检索出来。

  3、对于填有数据的游标,根据需要取出各行。

  4、在结束游标使用是,必须关闭游标。

  创建游标:  declare ordernumbers cursor for select  order_num form orders;

  这个存储过程仅是用declare语句定义和命名游标。存储过程处理完成之后,游标就消失。

  打开游标和关闭游标:open ordernumbers;  close ordernumbers;

例子:

drop procedure if exists p_5;
delimiter //
create procedure p_5(
     out out_pid varchar(10)
)
begin
    declare done bool default 0;
    declare c_1 cursor for select prod_id from products;
    declare continue handler for sqlstate '02000' set done=1;
    open c_1;
    fetch c_1 into out_pid;
    repeat
    select out_pid;
    fetch c_1 into out_pid;
    until done
    end repeat;
    close c_1;
end //
delimiter ;
set @out1:='';
call p_5(@out1);
select @out1;

 

原文地址:https://www.cnblogs.com/television/p/8365233.html