1、游标的作用及属性
游标的作用就是用于对查询数据库所返回的记录进行遍历,以便进行相应的操作;游标有下面这些属性:
a、游标是只读的,也就是不能更新它;
b、游标是不能滚动的,也就是只能在一个方向上进行遍历,不能在记录之间随意进退,不能跳过某些记录;
c、避免在已经打开游标的表上更新数据。
2、如何使用游标
使用游标需要遵循下面步骤:
a、首先用declare语句声明一个游标
declare cursor_name cursor for select_statement;
上面这条语句就对,我们执行的select语句返回的记录指定了一个游标 b、其次需要使用open语句来打开上面你定义的游标
open cursor_name;
c、接下来你可以用fetch语句来获得下一行数据,并且游标也将移动到对应的记录上(这个就类似java里面的那个iterator)。
fetch cursor_name into variable list;
d、然后最后当我们所需要进行的操作都结束后我们要把游标释放掉。
close cursor_name;
在循环游标时需要注意的是,使用定义一个针对not found的条件处理函数(condition handler)来避免出现“no data to fetch”这样的错误,条件处理函数就是当某种条件产生时所执行的代码,这里当我们游标指到记录的末尾时,便达到not found这样条件,这个时候我们希望继续进行后面的操作,所以我们会在下面的代码中看到一个continue。如:
declare continue handler for not found set no_more_products = 1
实例:
delimiter $$drop procedure if exists getuserinfo $$create procedure getuserinfo(in date_day datetime)-- -- 实例-- mysql存储过程名为:getuserinfo-- 参数为:date_day日期格式:2008-03-08-- begindeclare _username varchar(12); -- 用户名declare _chinese int ; -- 语文declare _math int ; -- 数学declare done int;-- 定义游标declare rs_cursor cursor for select username,chinese,math from userinfo where datediff(createdate, date_day)=0;declare continue handler for not found set done=1;-- 获取昨天的日期if date_day is null then set date_day = date_add(now(),interval -1 day);end if;open rs_cursor; cursor_loop:loop fetch rs_cursor into _username, _chinese, _math; -- 取数据 if done=1 then leave cursor_loop; end if;-- 更新表 update infosum set total=_chinese+_math where username=_username;end loop cursor_loop;close rs_cursor; end$$delimiter ;
