一:使用游标
(一):声明游标。
delare cursor_name cursor for select_statement;
解释:cursor_name是游标的名字 ;select_statement表示select语句。因为游标需要遍历结果集的每一行,增加了服务器的负担,导致游标的效率并不高效,。如果使用游标操作的数据超过1万行,那么应该采用其他方式,另外使用了游标,应该避免在游标循环中进行表连接操作。
(二):打开游标
open cursor_name
(三):使用游标
fetch cursor_name into var_name[,var_name]......
在上述语句中,将参数游标cursor_name中的select语句的执行结果保存到参数变量var_name中。变量参数var_name必须在游标使用之前定义。使用游标类似高级语言中的数组遍历,当第一次使用游标时,此时游标指向结果集的第一天记录的前边。
(四):关闭游标
close cursor_name;
例子:
delimiter $$
create procedure p()
begin
declare id int;
declare flag int;
declare num int ;
declare test_cursor cursor for select student_id from students_info;//创建游标
declare continue handler for not found set flag=1;//当查询不到内容时设置flag=1;
set num=0;
set flag=0;
open test_cursor;//打开游标
fetch test_cursor into id;//把游标的内容给id
while flag<>1 do
if id >2 then
set num=num+1;
end if;
fetch test_cursor into id;
end while;
close test_cursor;
select num;
end$$
demiliter ;