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

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章