一、游标
定义:存储在MySQL服务器上的数据库查询,是一种被select语句检索出来的结果集。
作用:方便在检索出来的结果集中前进或后退一行或多行。
游标主要用于交互式应用;MySQL中的游标只能用于存储过程(和函数)。
1、创建游标
游标使用declare语句创建;declare命名游标,并定义响应的select语句,根据需要带where和其他子句;例如:
create procedure processorders()
begin
declare ordernumbers CURSOR
for
select order_num from orders;
end;
这个存储过程中,declare定义和命名了游标ordernumbers,存储过程处理完成后,游标消失(因为它局限于存储过程内)。
2、打开和关闭游标
游标使用open cursor语句来打开,例如:
open ordernumbers;
在处理open语句时执行查询,存储检索出的数据以供浏览和滚动;
游标处理完成时,使用close语句关闭,例如:
close ordernumbers;
close释放游标使用的所有内部内存和资源,因此在每个游标不在需要时都应该关闭。
PS:一个游标关闭后,如果没有重新打开,则不能使用;但如果该游标被声明过,则不需要再次声明,用open语句打开使用即可。
如果不明确游标是否关闭,MySQL将会在到达end语句时自动关闭该游标;比如:
create procedure processorders()
begin
-- declare the cursor
declare ordernumbers cursor
for
select order_num from orders;
-- open the cursor
open ordernumbers;
-- close the cursor
close ordernumbers;
end;
这个存储过程声明、打开、关闭一个游标,但对检索出的数据没任何操作。
3、使用游标数据
游标被打开后,使用fetch语句分别访问