MYSQL使用游标

一:使用游标

            (一):声明游标。

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 ;

                    






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值