数据库之存储过程中的3种循环⽅法
在MySQL存储过程的语句中有三个标准的循环⽅式:WHILE循环,LOOP循环以及REPEAT循环。
这⼏个循环语句的格式如下:
WHILE……DO……END WHILE
create procedure pro10()
大学美育begin
declare i int;
t i=0;
while i<5 do
inrt into t1(filed) values(i);
t i=i+1;
苹果树作文
end while;
end;
REPEAT……UNTIL END REPEAT
create procedure pro11()
begin
declare i int default 0;
repeat
inrt into t1(filed) values(i);
t i=i+1;
until i>=5
end repeat;
end;
LOOP……END LOOP
create procedure pro12()
begin
declare i int default 0;
loop_label: loop
烫伤处理方法inrt into t1(filed) values(i);
t 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
t i=i+1;
iterate loop_label;
end if;
inrt into t1(filed) values(i);
t 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;//,结束整个存储过程。