mysql while迴圈多輸出一行原因解析

2021-08-28 06:59:10 字數 2032 閱讀 7229

有這樣乙個儲存過程:

drop procedure if exists tmall_test;

delimiter  //

create  procedure `tmall_test`()

begin

declare done tinyint default 0;

declare u_id int(11); 

declare cs cursor for select distinct comm_sal from sal where 1=1;

declare continue handler for not found set done=1;

open cs;

while done<>1 

dofetch cs into u_id;

insert into ss  values (u_id);

end while;

close cs;

end//

delimiter ;

但是結果總是這樣:

mysql> select * from ss;

+------+

| u_id |

+------+

|  101 |

|  200 |

|  500 |

|  150 |

|  450 |

|  322 |

|  322 |

+------+

7 rows in set (0.00 sec)

表中記錄只有6條,這裡有7條,最後重複一條。

分析問題。

當取了6條記錄,最後一條322的時候,done是為0的。

open cs;

while done<>1       #滿足條件,執行迴圈。

dofetch cs into u_id;     #拿不到了,為空了,這時候set done=1.

insert into ss  values (u_id);    #又被執行了一次,那麼這時候的uid就是上一次最後的u_id。

end while;        #結束。

原因:假設查詢出來了3條資料,設定到游標中。最後游標讀取完畢的時候, 也就是讀到第三行時,no還是0,進入迴圈,這時fetch游標資料,已經抓取不到資料了,把no設定為1,但是 下面的 select concat(p_id,'-',counter,'-',no) ; 還是會執行一次,故多迴圈了一次

這是while條件判斷的問題。或是for,until也可能有同樣的問題。

改用其他迴圈loop,

解決方法:

drop procedure if exists tmall_test;

delimiter  //

create  procedure `tmall_test`()

begin

declare done tinyint default 0;

declare u_id int(11); 

declare cs cursor for select distinct comm_sal from sal where 1=1;

declare continue handler for not found set done=1;

open cs;

while done<>1 

dofetch cs into u_id;

if done<>1 then        #執行fetch之後,這裡判斷一下done的值,再執行。

insert into ss  values (u_id);

end if;

end while;

close cs;

end//

delimiter ;

你還可以在這個程式中,新增計數,來看while,for,until,loop迴圈了多少次。

set cnt = 0;# 計數,迴圈了幾次  

open cs; # 開啟游標  

while no <> 1 do # 迴圈讀取游標資料  

set cnt = cnt +1;  

MySQL while迴圈(儲存過程 函式)

table structure for students drop table if exists students create table students id int not null auto increment comment 主鍵id name varchar 255 characte...

keras搬磚系列 keras多輸入多輸出模型

使用函式式模型的乙個典型的場景就是搭建多輸入,多輸出模型。考慮這樣乙個模型,希望 一條新聞會被 和點讚多少次。模型的主要輸入是新聞的本身,也就是乙個詞語的序列,但是我們可能還需要額外的輸入,新聞發布的日期等,所以這個模型的損失函式將會由兩個部分組成,輔助的損失函式基於新聞本身做出的 的情況,主損失函...

多輸出感知機及其梯度

目錄 對於多輸出感知機,每個輸出元只和輸出元上的x和w和 有關。import tensorflow as tfx tf.random.normal 2,4 w tf.random.normal 4,3 b tf.zeros 3 y tf.constant 2,0 with tf.gradientta...