1,while循环
语法:
先判定循环是有条件的循环控制语句,满足条件后,再执行循环体中的sql语句
while 条件 do
sql语句
end while;
练习:
# 传入一个参数n,计算1+2+3+...+n的值
create procedure p5(in n int)
begin
declare total int default 0;
while n > 0 do
set total := total + n;
set n := n - 1;
end while;
select total;
end;
drop procedure p5;
call p5(100);
2,repeat
repeat是有条件的循环控制语句,当满足条件的时候推出循环,不满足则继续下一次循环
语法:
repeat
sql语句
until 条件
end repeat;
练习:
# 传入一个参数n,计算1+2+3+...+n的值
create procedure p6(in n int)
begin
declare total int default 0;
repeat
set total := total + n;
set n := n - 1;
until n <= 0
end repeat;
select total;
end;
drop procedure p6;
call p6(100);
3,loop
loop,简单的循环语句,如果不在sql逻辑中增加退出循环的条件,可以用其来实现死循环。
语法:
-- [begin_label:] 、[begin_label:]用于标记该循环
[begin_label:] loop
sql逻辑
end loop [end_label];
leave label; --配合循环使用,退出指定标记的循环体
iterate label; --必须在循环中使用,作用是跳过当前循环剩下的语句,直接进入下一次循环
练习:
# 循环 loop
# 传入一个参数n,计算1+2+3+...+n的值
create procedure p7(in n int)
begin
declare total int default 0;
sum: loop
if n = 0 then
leave sum;
end if;
set total := total + n;
set n := n - 1;
end loop sum;
select total;
end;
call p7(100);
# 创建一个存储过程传入一个参数n,0~n内偶数的累加值
create procedure p8(in n int)
begin
declare total int default 0;
sum: loop
if n = 0 then
leave sum;
end if;
if n%2 = 1 then # 当n为奇数时,跳过本次循环,不执行下边的sql
set n := n - 1;
iterate sum;
end if;
set total := total + n;
set n := n - 1;
end loop sum;
select total;
end;
drop procedure p8;
call p8(100);