在MySQL存储过程的语句中有三个标准的循环方式:WHILE循环,LOOP循环以及REPEAT循环。
这几个循环语句的格式如下:
WHILE……DO……END WHILE
create procedure pro10() begin declare i int; set i=0; while i<5 do insert into t1(filed) values(i); set i=i+1; end while; end;
REPEAT……UNTIL END REPEAT
create procedure pro11() begin declare i int default 0; repeat insert into t1(filed) values(i); set i=i+1; until i>=5 end repeat; end;
LOOP……END LOOP
create procedure pro12() begin declare i int default 0; loop_label: loop insert into t1(filed) values(i); set i=i+1; if i>=5 then leave loop_label; end if; end loop; end;
Labels标号 和 END Labels 结束标号
在使用loop的时候,使用到的labels标号,对于labels可以用到while,loop,rrepeat等循环控制语句中。而且有必要好好认识一下lables!!
create procedure pro13() label_1:begin label_2:while 0=1 do leave label_2;end while; label_3:repeat leave label_3;until 0=0 end repeat; label_4:loop leave label_4;end loop; end;
上面这里例子显示了可以在BEGIN、WHILE、REPEAT或者LOOP语句前使用语句标号,语句标号 只能在合法的语句前使用,所以LEAVE label_3意味着离开语句标号名为label_3的语句或符合语句。
其实,也可以使用END labels来表示标号结束符。
create procedure pro14() label_1:begin label_2:while 0=1 do leave label_2;end while label_2; label_3:repeat leave label_3;until 0=0 end repeat label_3; label_4:loop leave label_4;end loop label_4; end label_1;
上面就是使用了标号结束符,其实这个结束标号并不是十分有用,而且他必须和开始定义的标号名字一样,否则就会报错。如果要养成一个良好的编程习惯方便他人阅读的话,可以使用这个标号结束符。
ITERATE 迭代
如果是在ITERATE语句,即迭代语句中的话,就必须使用LEAVE语句。ITERATE只能出现在LOOP,REPEAT和WHILE语句中,它的意思是“再次循环”,例如:
create procedure pro15() 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;
存储过程的功能:数据库中将插入数值:0,1,2,4。
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;//,结束整个存储过程。