之前学数据库一直看不懂游标的概念,最近学习了,补充一下。
原贴:https://www.cnblogs.com/progor/p/8875100.html
如果你前面看过mysql函数,会发现无法使用返回多行结果的语句。但如果你又确实想要使用时,就需要使用到游标,游标可以帮你选择出某个结果(这样就可以做到返回单个结果)。
另外,使用游标也可以轻易的取出在检索出来的行中前进或后退一行或多行的结果。
游标可以遍历返回的多行结果。
补充:
Mysql中游标只适用于存储过程以及函数。
1、游标的概念(Cursor)
一条sql,对应N条资源,取出资源的接口,就是游标,沿着游标,可以一次取出1行。如果开发过安卓的同学应该知道有一个Api是Cursor,也是读取SQLite数据库用的,和这个有点类似。
2、使用游标的步骤
(1)声明
使用declare进行声明
declare 游标名 cursor for select_statement
(2)打开游标
使用open进行打开
open 游标名
(3)从游标中取值
使用fetch进行取值
fetch 游标名 into var1,var2[,…] --将取到的一行赋值给多个变量
(4)关闭游标
使用close关闭游标
close 游标名
delimiter $
select * from s2$
select * from s2 where id=5$
create procedure p1(in i integer,out a1 char(9),out b1 char(9))
begin
declare mc cursor for select a,b from s2; #貌似begin后面第一句必须是这个
set @co=0;
open mc;
myloop:loop fetch mc into a1,b1;
select a1,b1,@co;
if @co>3 then
leave myloop;
end if;
set @co=@co+1;
end loop;
close mc;
end;
$
delimiter ;
set @a=0,@b=0;
call p1(5,@a,@b);
select @a,@b;
如果不用break循环可以用下面的写法,不用给loop起名了
delimiter $
select * from s2$
select * from s2 where id=5$
create procedure p1(in i integer,out a1 char(9),out b1 char(9))
begin
declare mc cursor for select a,b from s2; #貌似begin后面第一句必须是这个
open mc;
loop fetch mc into a1,b1;
select a1,b1;
end loop;
close mc;
end;
$
delimiter ;
set @a=0,@b=0;
call p1(5,@a,@b);
select @a,@b;