游标

游标(cursor)

基本概念

  • 游标是一个存储在MySQL服务器上的数据库查询,它不是一条select语句,而是被该语句检索出来的结果集。在存储了游标之后,可以对结果集进行逐行读取的操作。
  • 使用游标注意:
  • 在使用游标之前,必须要声明(定义)它。这个过程实际上没有检索数据,知识定义要使用的select语句。
  • 声明之后,必须打开游标使用。这个过程用前面定义的select语句将数据检索出来。
  • 对于填有数据的游标,根据需要取出(检索)各行。
  • 在结束游标使用时必须关闭游标
  • MySQL中游标只能用于存储过程(和函数)。

游标使用过程

  • 创建游标
    declare cursor_name cursor for select...
  • 打开和关闭游标
    open/close cursor_name;
  • 使用游标数据
    利用fetch语句分别访问它的每一行,fetch语句指定检索什么数据,检索出来的数据存储在什么地方,它还向前移动游标中的内部指针,使下一条fetch语句检索下一行。
    fetch cursor_name into tmp;

游标使用演示

create procedure processorders()
begin 
declare done boolean default 0;
declare o int;
declare t decimal(8,2);

declare ordernumbers cursor 
        for 
        select order_num from orders;

declare continue handler for sqlstate '02000' set done=1;//'02000'指未找到

create table if not exists ordertotals(order_num int ,total decimal(8,2));
//打开游标 
open ordernumbers;

repeat
    fetch ordernumbers into o;
    call ordertotal(o,1,t);
    insert into ordertotals(order_num,total) values(o,t);
until done end repeat;
close ordernumbers;

end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容