Mysql学习笔记

Mysql 学习笔记(六)

游标(Cursor)

是系统为用户开设的一个数据缓冲区,存放 SQL 语句的执行结果。每个游标区都有 一个名字。用户可以用 SQL 语句逐一从游标中获取记录,并赋给主变量,交由主语言进一 步处理。

游标的特性:

➢ READ ONLY 只读,只能取值而不能赋值;

➢ NOT SCROOLABLE 不可回滚,只能顺序读取;

➢ ASENSITIVE 敏感,不能在已经打开游标的表上执行 update 事务;

游标操作:

➢ 声明游标: DECLARE cursor_name CURSOR FOR select_statement 这个语句声明一个光标。也可以在子程序中定义多个光标,但是一个 块中的每一个光标必须有唯一的名字。

➢ 打开游标: OPEN cursor_name 游标 FETCH:FETCH cursor_name INTO var_name [, var_name] ... 这个语句用指定的打开光标读取下一行(如果有下一行的话),并且前进光标指针。

➢ 关闭游标 CLOSE: CLOSE cursor_name 这个语句关闭先前打开的光标。如果未被明确地关闭,光标在它被声明的复合语句 的末尾被关闭。


(1)游标的使用方法

1)声明一个游标

declare 游标名 cursor for select_statement;

2)打开一个游标

open 游标名;

3)取值

fetch 游标名 into var1,var2[,...];

4)关闭

close 游标名;

(2)实例

delimiter //

create procedure p3()

begin

declare row_sno varchar(10);

declare row_sname varchar(20);

declare row_sage int;

declare row_ssex varchar(5);

declare ergodic int default 0;

declare getstudent cursor for select sno,sname,sage,ssex from student;

declare continue handler for not found set ergodic=1;

open getstudent;

repeat

fetch getstudent into row_sno,row_sname,row_sage,row_ssex;

select row_sno,row_sname,row_sage,row_ssex;

until ergodic=1 end repeat;

close getstudent;

end //

call p3() // 


未使用游标--1
未使用游标--2
游标--1
游标--2
游标--3
游标--4

从上面的图中可以看出最后一条数据出现了两次

exit与continue的区别是:exit触发后,后面的语句不再执行,而continue还需要继续执行。

下面使用exit

create procedure p4()

begin

declare row_sno varchar(10);

declare row_sname varchar(20);

declare row_sage int;

declare row_ssex varchar(5);

declare ergodic int default 0;

declare getstudent cursor for select sno,sname,sage,ssex from student;

declare exit handler for not found set ergodic=1;

open getstudent;

repeat

fetch getstudent into row_sno,row_sname,row_sage,row_ssex;

select row_sno,row_sname,row_sage,row_ssex;

until ergodic=1 end repeat;

close getstudent;

 end  //

游标--5
游标--6
游标--7
游标--8

由上图可以看出,最后一条数据没有出现两次。

注:本文参考http://blog.csdn.net/xushouwei/article/details/52201360

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

推荐阅读更多精彩内容

  • Mysql 学习笔记(五) 触发器(Trigger) ➢它是个特殊的存储过程,它的执行不是由程序调用,也不是手工启...
    二十四小时爱你阅读 268评论 1 1
  • Mysql 学习笔记(三) 索引(index) (1)索引是一个单独的、物理的数据库结构,它是某个表中一列或若干列...
    二十四小时爱你阅读 305评论 0 1
  • Mysql 学习笔记(四) 视图(View) ➢从用户角度来看,一个视图是从一个特定的角度来查看数据库中的数据。从...
    二十四小时爱你阅读 152评论 1 1
  • 一、SQL 的执行逻辑 这一节的原文地址是lifepoem 首先我们来看一条完整的SQL语句 可以看到,SQL语言...
    JSong1122阅读 614评论 0 7
  • 一、存储过程概念 什么是存储过程 一组为了完成特定功能的SQL 语句集。更加直白的理解:存储过程可以说是一个记录集...
    maxwellyue阅读 589评论 0 3