美文网首页
daily -- mysql 基础 循环语句

daily -- mysql 基础 循环语句

作者: JackSpeed | 来源:发表于2021-04-01 10:28 被阅读0次

循环语句必须在begin end 语句体中


循环语句类型

  • while
  • loop
  • repeat

循环控制

  • iterate
    类似于java的continue,结束当前循环,继续下一次循环
  • leave
    类似于java中的break,结束当前结构体的循环

while循环

结构1

while 循环条件 do
循环体;
end while;

结构2

标签: while 循环条件 do
循环体;
end while 标签;

example

delimiter $
create procedure test_while(IN addCount INT)
begin
    declare i int default 1;
    while i <= addCount
        do
            insert into t_test(user_name, user_age)
            values (concat('name', i), i);
            set i = i + 1;
        end while;
end $

set @counts = 100;
call test_while(@counts);

带IF条件

truncate table t_test;
drop procedure if exists test_while;
delimiter $
create procedure test_while(IN addCount INT)
begin
    declare i int default 1;
    while i <= addCount
        do
            if i > 50 then
                insert into t_test(user_name, user_age)
                values (concat('老三', i), i);
            else
                insert into t_test(user_name, user_age)
                values (concat('老大', i), i);
            end if;
            set i = i + 1;
        end while;
end $

set @counts = 100;
call test_while(@counts);

使用leave控制语句

truncate table t_test;
drop procedure if exists test_while;
delimiter $
create procedure test_while(IN addCount INT)
begin
    declare i int default 1;
    addwx: while i <= addCount
        do
            if i > 50 then
                leave addwx;
            else
                insert into t_test(user_name, user_age)
                values (concat('name', i), i);
            end if;
            set i = i + 1;
        end while addwx;
end $

set @counts = 100;
call test_while(@counts);

使用iterate,i为偶数时写入数据

truncate table t_test;
drop procedure if exists test_while;
delimiter $
create procedure test_while(IN addCount INT)
begin
    declare i int default 1;
    addwx:
    while i <= addCount
        do
            set i = i + 1; bvv 
            if i % 2 = 1 then
                iterate addwx;
            else
                insert into t_test(user_name, user_age)
                values (concat('name', i), i);
            end if;

        end while addwx;
end $

set @counts = 100;
call test_while(@counts);

loop循环 (常用语模拟死循环场景)

标签: loop
循环体;
end loop 标签;

repeat循环

标签: repeat
循环体;
until 结束循环的条件;
end repeat 标签;

相关文章

网友评论

      本文标题:daily -- mysql 基础 循环语句

      本文链接:https://www.haomeiwen.com/subject/wzenhltx.html