zoukankan      html  css  js  c++  java
  • mysql 游标的使用总结

    一、游标的基本概念

           游标:游标是一个存储在Mysql服务器上的数据库查询,它不是一条select语句,而是被该语句检索出来的结果集。

          本人,学习游标中,曾遇到一个问题,循环总是最后多执行一次。下面分析程序,这个是一个sql脚本程序

           #if d=0 then   #end if; 注释掉这两行时,会发现,游标中的repeat循环总是多执行一次。

           vendors 表中之前的数据为:

                                                                           图1

    二、程序及结果分析

    delimiter //
    create procedure procursor(in num int)
    begin
      declare d boolean default 0;
      declare o int;
      declare t int;
      declare c int default 0;
      declare mycur cursor for select vend_id from vendors;
      declare continue handler for sqlstate '02000' set d =1 ;
      create table if not exists results(re_id int,re_num int);
      open mycur;
     repeat
      fetch mycur into o;
    #if d=0 then
      select o;
      # set t=o*num;
      insert into results values(o,num*o);
      set c=c+1;
     select d;
    # end if;
     until d end repeat;
       close mycur;
    select * from results;
    select c;
    end //
     delimiter ;

    注释 #if d=0 then 和# end if;  执行以上sql语句后,call procursor(100); 执行结果如图2所示;发现,游标的循环总是多执行了一次,执行了4次疑问,

    分析发现,原因在于,最后一次fetch mycur into o;时,mycur 为空 ,o值未更改,所以,最后一组值,多执行了一次。此时若检测d的值,发现d为1。将#if d=0 then和# end if;注释去掉,做一个条件判断后的结果如图3所示。

    结果正确大笑


              

                          图2                                                                                                图3

  • 相关阅读:
    二分查找小结
    FZU みねちゃんの修罗场(从一堆出现三次的数中找出出现两次的数)
    《C陷阱与缺陷》杂记
    HDU 1846 Brave Game(巴什博弈)
    【转载】并查集详解
    第七次作业——学末总结
    STL之vector
    fzuoop期中练习
    MFC 文件对话框
    第六次作业——利用MFC实现计算器图形界面以及简单四则运算表达式批处理
  • 原文地址:https://www.cnblogs.com/chhuach2005/p/3961699.html
Copyright © 2011-2022 走看看