MySQL进阶之循环控制(WHILE,REPEAT,LOOP)

WHILE

while 循环是有条件的循环控制语句。满足条件后,再执行循环体中的SQL语句。

-- 先判定条件,如果条件为true,则执行逻辑,否则,不执行逻辑
WHILE 条件 DO
SQL逻辑...
END WHILE;

案例:

create procedure p7(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;

call p7(100);

 

REPEAT

repeat是有条件的循环控制语句, 当满足until声明的条件的时候,则退出循环 。

-- 先执行一次逻辑,然后判定UNTIL条件是否满足,如果满足,则退出。如果不满足,则继续下一次循环
REPEAT
SQL逻辑...
UNTIL 条件
END REPEAT;

 案例:

create procedure p8(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;

call p8(100);

 

LOOP

LOOP 实现简单的循环,如果不在SQL逻辑中增加退出循环的条件,可以用其来实现简单的死循环。 LOOP可以配合一下两个语句使用:

  • LEAVE :配合循环使用,退出循环。 (相当于break)

  • ITERATE:必须用在循环中,作用是跳过当前循环剩下的语句,直接进入下一次循环。(相当于continue)

[begin_label:] LOOP
SQL逻辑...
END LOOP [end_label];

LEAVE label; -- 退出指定标记的循环体
ITERATE label; -- 直接进入下一次循环
begin_label,end_label,label 指的都是我们所自定义的标记。

案例:

-- A. 定义局部变量, 记录累加之后的值;
-- B. 每循环一次, 就会对n进行-1 , 如果n减到0, 则退出循环 ----> leave xx
create procedure p9(in n int)
    begin
        declare total int default 0;

        sun:loop
            if n <= 0 then
                leave sun;
            end if;
            set total := total + n;
            set n := n - 1;

        end loop;
    select total;
end;

call p9(100);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

元气满满的热码式

感谢您的支持!我会继续努力发布

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值