1、游标的作用:
1.1 如果你前面看过mysql函数,会发现无法使用返回多行结果的语句。但如果你又确实想要使用时,就需要使用到游标,游标可以帮你选择出某个结果(这样就可以做到返回单个结果)。
1.2 使用游标也可以轻易的取出在检索出来的行中前进或后退一行或多行的结果。
1.3 游标可以遍历返回的多行结果。
1.4 Mysql中游标只适用于存储过程以及函数。

2、游标的定义与语法:

1.定义游标:declare 游标名 cursor for select语句;
2.打开游标:open 游标名;
获取结果:fetch 游标名 into 变量名[,变量名];
关闭游标:close 游标名;
--在windows系统中写存储过程时,如果需要使用declare声明变量,需要添加这个关键字,否则会报错。
delimiter //
drop procedure if exists StatisticStore;
CREATE PROCEDURE StatisticStore()
BEGIN
	--创建接收游标数据的变量
	declare c int;
	declare n varchar(20);
	--创建总数变量
	declare total int default 0;
	--创建结束标志变量
	declare done int default false;
	--创建游标
	declare cur cursor for select name,count from store where name = 'iphone';
	--指定游标循环结束时的返回值
	declare continue HANDLER for not found set done = true;
	--设置初始值
	set total = 0;
	--打开游标
	open cur;
	--开始循环游标里的数据
	read_loop:loop
	--根据游标当前指向的一条数据
	fetch cur into n,c;
	--判断游标的循环是否结束
	if done then
		leave read_loop;	--跳出游标循环
	end if;
	--获取一条数据时,将count值进行累加操作,这里可以做任意你想做的操作,
	set total = total + c;
	--结束游标循环
	end loop;
	--关闭游标
	close cur;
 
	--输出结果
	select total;
END;
--调用存储过程
call StatisticStore();

fetch是获取游标当前指向的数据行,并将指针指向下一行,当游标已经指向最后一行时继续执行会造成游标溢出,可以定义一个变量来控制越界。如:
declare continue handler
实例:

declare continue handler for NOT FOUND statement;

游标循环实例:

首先应该创建游标,然后打开游标后,应先手动进行fetch操作获取到一行数据,然后再通过循环,在循环里先做处理内容,后进行fetch操作。这样如果在手动获取数据的期间就没有获得到数据的话,就会执行have = 0,如果是repeat循环,然后进入repeat循环,先输出null数据,最后又进行获取,这样运行到until时就会退出循环;如果是while循环,压根就不进去while循环里,就不会有任何1行输出。

repeat循环:

create procedure p17()
begin
  declare row_gid int;
  declare row_name varchar(20);
  declare row_num int;
  declare have int default 1;
  declare getgoods cursor for select gid,name,num from goods where 0;
  declare continue handler for NOT FOUND set have:= 0;
  open getgoods;
  fetch getgoods into row_gid,row_name,row_num;
  repeat 
  select row_name,row_num;
    fetch getgoods into row_gid,row_name,row_num;
  until have = 0 end repeat;
  close getgoods;
end$

while循环:

create procedure p18()
begin
  declare row_gid int;
  declare row_name varchar(20);
  declare row_num int;
  declare have int default 1;
  declare getgoods cursor for select gid,name,num from goods where 0;
  declare continue handler for NOT FOUND set have:= 0;
  open getgoods;
  fetch getgoods into row_gid,row_name,row_num;
  while have = 1 do 
  select row_name,row_num;
    fetch getgoods into row_gid,row_name,row_num;
  end while;
  close getgoods;
end$


本章是本人在使用游标,学了多个博客整理出来的