MySQL儲存過程中的3種迴圈
阿新 • • 發佈:2019-01-31
-> begin
-> declare i int default 0;
-> loop_label:loop
-> if i=3 then
-> set i=i+1;
-> iterate loop_label;
-> end if;
-> insert into t1(filed) values(i);
-> set i=i+1;
-> if i>=5 then
-> leave loop_label;
-> end if;
-> end loop;
-> end;//
Query OK, 0 rows affected (0.00 sec)
iterate語句和leave語句一樣,也是在迴圈內部使用,它有點類似於C/C++語言中的continue。
那麼這個儲存程式是怎麼執行的的?首先i的值為0,條件判斷語句if i=3 then判斷為假,跳過if語段,向資料庫中插入0,然後i+1,同樣後面的if i>=5 then判斷也為假,也跳過;繼續迴圈,同樣插入1和2;在i=3的時候條件判斷語句if i=3 then判斷為真,執行i=i+1,i值為4,然後執行迭代iterate loop_label;,即語句執行到iterate loop_label;後直接跳到if i=3 then判斷語句,執行判斷,這個時候由於i=4,if i=3 then判斷為假,跳過IF語段,將4新增到表中,i變為5,條件判斷if i>=5 then判斷為真,執行leave loop_label;跳出loop迴圈,然後執行end;//,結束整個儲存過程。
綜上所述,資料庫中將插入數值:0,1,2,4。執行儲存過程,並檢視結果:|
mysql> delete from t1//
Query OK, 5 rows affected (0.00 sec)