MySQL存储过程中的3种循环(二)
-> 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 looplabel;,即语句执行到iterate looplabel;后直接跳到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)
mysql> call pro15// Query OK, 1 row affected (0.00 sec)
mysql> select * from t1// +——-+ | filed | +——-+ | 0 | | 1 | | 2 | | 4 | +——-+ 4 rows in set (0.00 sec)
和我们上面分析的结果一样,只插入了数值0,1,2,4。