流程控制一般三种:顺序,分支,循环

分支

1.if函数

语法:if(exp1,exp2,exp3)
执行顺序:
如果表达式1即exp1成立,则if函数返回表达式2即exp2的值,否则返回表达式3即exp3的值

2.case结构

语法:case [变量|表达式|字段]#区间判断的时候省略
when 要判断的值或要判断的条件1 then 返回值1或语句1;
when 要判断的值 then 返回值2或语句2;
when 要判断的值 then 返回值3或语句3;

else 要返回的值n
END CASE;
与其他语言相比,没有break,但是;默认和break功能一样

#case案例
create procedure test_case(IN score INT)
begin
    case
    when score>=90 and score<=100 then select 'a';
    when score>=80 then select 'b';
    when score>=60 then select 'c';
    else select 'd';
    end case;
end $

3.if结构

语法:
if 条件1 then 语句;
elseif 条件2 then 语句2;
[else 语句n;]
end if
只能在begin end里用

#if结构案例
create function test_if(score INT) returns char
begin
    if score>=90 and score<=100 then return 'a';
    elseif score>=80 then return 'b';
    elseif score>=60 then return 'c';
    else return 'd';
    end if;
end $

4.循环

分类:while,loop,repeat
控制:iterate类似continue:结束本次循环,进入下一次,
leave类似break:结束当前所在循环

1.while语法

[标记:] while 条件 do 循环体;
end while [标记];

2.loop语法

[标记:] loop
循环体;
end loop [标记];
用来模拟简单的死循环

3.repeat语法

[标记:] repeat
循环体;
until 结束循环的条件
end repeat [标记];

#while案例:根据传入次数n,向table1插入n条记录
##没有返回值,所以用procedure而不用function
create procedure pro_while1(IN insertCount INT)
begin
    declare i int default 1;
        while i<=insertCount do
        insert into table1(name)values(concat("a1",i));
        set i=i+1;
    end while;
end $

call pro_while1(3)$
#leave案例:根据传入次数n,向table1插入n条记录,如果次数>=20,则停止
##没有返回值,所以用procedure而不用function
truncate table table1$
drop procedure pro_while1$
create procedure pro_while1(IN insertCount INT)
begin
    declare i int default 1;
        label1:while i<=insertCount do
        insert into table1(name)values(concat("a1",i));
        IF i>=20 then leave label1;
        end IF;
        set i=i+1;
    end while label1;
end $

call pro_while1(3)$
#iterate案例:偶数次插入
create procedure pro_it(IN count INT)
begin
    declare i int default 0;
    a:while i<count do
        set i=i+1;
        if mod(i,2)!=0 then
                iterate a;
        end if;
        insert into table1(name)values(concat("a1",i));
    end while a;    
end$