mysql之流程控制结构

顺序结构

程序从上往下依次执行

分支结构

程序从两条或者多条路径中选择一条去执行。
使用if then
elseif then
else

if函数

if(表达式1,表达式1,表达式1)
执行下顺序:如果表达式1成立,则返回表达式2的值,否则返回表达式3的值

case结构

1.类似于java中的switch语句,一般用于实现的等值判断。

case 变量|表达式
when 要判断的值 then 返回的值1
when 要判断的值 then 返回的值2
else 要返回的值n
end
case 变量|表达式
when 要判断的值 then 返回的语句1
when 要判断的值 then 返回的语句2
else 要返回的语句n
end case

2.类似于java中的多重if语句,一般用于实现区间判断。

case 
when 要判断的值 then 返回的值1
when 要判断的值 then 返回的值2
else 要返回的值n
end
case 
when 要判断的值 then 返回的语句1
when 要判断的值 then 返回的语句2
else 要返回的语句n
end case

特点:
1.
可以💺表达式,嵌套在其他语句中使用,可以放在任何地方,begin end中或者begin end外面
可以作为独立的语句使用,只能放在begin end中。
2.
如果when中的值满足或者条件成立,则执行对应的then后面的语句,并且结束case
如果都不满足,则执行else中的语句或者值
3.
else可以省略,如果else省略了,并且所有的when条件都不满足,则返回null

create procedure test_case(in score int)
begin
    case
        when score>=90 then select 'A';
        when score>=80 then select 'B';
        when score>=60 then select 'C';
        else select 'D';
        end case;
end;

call test_case(95);

循环结构

程序在满足一定条件的基础上,重复执行一段代码
while loop repeat

循环控制:
iterate 类似于continue,继续,结束本次循环,进行下一次
leave 类似于break,跳出,结束当前的循环

while

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

loop

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

可以用来模拟简单的死循环

repeat

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

案例:批量插入,根据次数插入到admin表中多条记录

create procedure pro_while(in insertCount INT)
begin 
    declare i int default 1;
    a:while i<insertCount do
        insert into admin(username,password) values(concat('rose',i),'666');
        set i=i+1;
        end while a;
end;

call pro_while(100);



create procedure pro_while2(in insertCount INT)
begin 
    declare i int default 1;
    a:while i<insertCount do
        insert into admin(username,password) values(concat('rose',i),'666');
       if i>=20 then leave a;
       end if;
        set i=i+1;
        end while a;
end;

call pro_while2(100);

create procedure pro_while3(in insertCount INT)
begin
    declare i int default 0;
    a:while i<insertCount do
       set i=i+1;
        if mod(1,2)!=0 then iterate a;
       end if;
        insert into admin(username,password) values(concat('rose',i),'666');
        end while a;
end;

call pro_while3(100);
create procedure test_randstr_insert(in insertCount int)
begin 
    declare i int default 1;
    declare str varchar(26) default 'abcdefg';
    declare startIndex int default 1;
    declare len int default 1;
    while i<insertCount do
        substr(str,startIndex,len);
        
        set len=floor(rand()*(20-startIndex+1)+1);
        set startIndex=floor(rand()*26+1);
        set i=i+1;
        end while;
end;
posted @ 2022-03-17 01:49  King-DA  阅读(31)  评论(0)    收藏  举报