游标是一个存储再MySQL服务器上的数据查询,它不是
一条select语句,而是被某一条select语句检索出来的结果集。
在存储了游标后,应用程序可以根据需要滚动或者浏览其中的数据。
简单一点理解,就像高级语言中的集合,用来存储一个结果集的东西。
##这里要注意一点:MySQL游标只能用于存储过程(和函数)
直接通过一个sql脚本来看:
对于存储过程还不知道的可以参看我这篇博客:存储过程初探
create procedure processorders()
begin
--declare local variables
declare done boolean default 0;
declare o int;
declare t decimal(8,2);
--declare the cursor
declare ordernumbers cursor
for
select order_num from orders;
--delare continue handler
declare continue handler for sqlstate '02000' set done = 1;
--create a table to store the results
create table if not exists ordertotals(
ordernum int,
total decimal(8,2)
);
--open the cursor
open ordernumbers;
--loop through all rows
repeat
--get order numbers
fetch ordernumbers into o;
--get the total for this order
call ordertotal(o,1,t);
--insert order and total into ordertotals
insert into ordertotals(order_num,total)
values(o,t)
--end of loop
until done end repeat;
--close the cursor
close ordernumbers;
end;
如上游标的用法:
创建游标
declare ordernumbers cursor
for
select order_num from orders;
就是把查询到的某一列的数据都放到order里面去。
使用游标前需要打开游标:
open ordernumbers;
用完后关闭使用close关键字;
循环语句使用技巧:
这条语句定义了一个continue handler,它是在条件出现时被执行的代码。
这里,它指出当sqlstate '02000'出现时,set done =1,
而sqlstate '02000'是一个未找到条件,当repeat由于没有更多的行提供循环
而不能继续时,就会出现这个条件。