mysql 游标总条数_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
總結
以上是生活随笔為你收集整理的mysql 游标总条数_mysql 游标的使用总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3 面向对象_Python3
- 下一篇: python if else用法同一行_