顺序、分支、循环

一、分支结构

1.if函数

语法:if(条件,值1,值2)
功能:实现双分支
应用在begin end中或外面

2.case结构

语法:

情况1:类似于switch

case 变量或表达式
when 值1 then 语句1;
when 值2 then 语句2;

else 语句n;
end

情况2:

case
when 条件1 then 语句1;
when 条件2 then 语句2;

else 语句n;
end
应用在begin end 中或外面

3.if结构

语法:

if 条件1 then 语句1;
elseif 条件2 then 语句2;
….
else 语句n;
end if;
功能:类似于多重if
只能应用在begin end 中

案例1:创建函数,实现传入成绩,如果成绩>90,返回A,如果成绩>80,返回B,如果成绩>60,返回C,否则返回D

  1. create function test_if(score float)returns char
  2. begin
  3. declare ch char default 'A';
  4. if score>90 then set ch='A';
  5. elseif score>80 then set ch='B';
  6. elseif score>70 then set ch='C';
  7. else set ch='D';
  8. end if;
  9. return ch;
  10. end
  11. select test_if(87);

案例2:创建存储过程,如果工资<2000,则删除,如果5000>工资>2000,则涨工资1000,否则涨工资500

create procedure test_if_pro(in sal double)
begin
    if sal<2000 then delete from employees where employees.salary=sal;
    elseif sal>=2000 and sal<5000 then update employees set salary=salary+1000 where employees.salary=sal;
    else update employees set salary=salary+500 where employees.salary=sal;
    end if;
end
call test_if_pro(2100);
select * from employees;

案例3:创建函数,实现传入成绩,如果成绩>90,返回A,如果成绩>80,返回B,如果成绩>60,返回C,否则返回D

create function test_case(score float)returns char
begin
    declare ch char default 'A';

    case
    when score>90 then set ch='A';
    when score>80 then set ch='B';
    when score>60 then set ch='C';
    else set ch='D';
    end case;

    return ch;
end
select test_case(56);

二、循环结构

分类:

while、loop、repeat

循环控制:

iterate类似于 continue,继续,结束本次循环,继续下一次
leave 类似于 break,跳出,结束当前所在的循环

1.while

语法:

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

联想:

while(循环条件){
循环体;
}

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

create procedure pro_while1(in insertCount int)
begin
    declare i int default 1;
    while i<=insertCount do
    insert into admin(username,password) values(concat('Rose',i),'666');
    set i=i+1;
    end while;
end
call pro_while1(100);
select count(1) from admin;

2.loop

语法:

【标签:】loop
循环体;
end loop 【标签】;
可以用来模拟简单的死循环

案例:批量插入,根据次数插入到admin表中多条记录,如果次数>20则停止

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

3.repeat

语法:

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

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

truncate table admin;
drop procedure test_while;
create procedure test_while(in insertCount int)
begin
    declare i int default 0;
    a:while i<=insertCount do
        set i=i+1;
        if mod(i,2)!=0 then iterate a;
        end if;
        INSERT INTO admin(username,`password`) VALUES(CONCAT('xiaohua',i),'0000');
    end while a;    
end
call test_while(100);
select count(1) from admin;