【MySQL】流程控制结构

分支结构

if 函数

效果参考三元运算符

select if(5<10, '大', '小'); -- 大

case 结构

  1. 作为表达式 → 嵌套在其他语句中使用 → 可以放在任何地方
  2. 作为独立的语句去使用 → 只能放在 begin end

方法1:效果参考 switch case 语句

case 字段|表达式|变量
when 常量1 then 返回值1 【语句1;】
when 常量2 then 返回值2 【语句2;】
else 默认返回值 【语句n;】 -- else 可以省略
end 【case;】 -- 没有满足的条件则返回 null

eg:查询各部门的总工资

select salary, departmentId,
    case departmentId
    when 1 then salary*1.1
    when 2 then salary*1.2
    when 3 then salary*1.3
    else salary
    end as '总工资'
from `employees`;

方法2:效果参考 if … else if … else 语句

case
when 条件1 then 返回值1 【语句1;】
when 条件2 then 返回值2 【语句2;】
else 默认返回值 【语句n;】 -- else 可以省略
end 【case;】 -- 没有满足的条件则返回 null

eg:查询员工的工资情况

select salary,
    case 
    when salary>20000 then 'A'
    when salary>15000 then 'B'
    when salary>10000 then 'C'
    else 'D'
    end as '工资等级'
from `employees`;

eg:创建存储过程,根据传入的成绩来显示等级

delimiter $
create procedure testCase(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 testCase(95) $ -- a

if 结构

只能应用在 begin end

if 条件1 then 语句1;
elseif 条件2 then 语句2;
...
[else 语句n;]
end if;

eg:创建函数,根据传入的成绩来显示等级

create function testIf(score int) returns char
begin
	if score>=90 then return 'a';
	elseif score>=80 then return 'b';
	elseif score>=60 then return 'c';
	else return 'd';
	end if;
end $

select testIf(66)$ -- c

循环结构

注意:只能放在 begin end 语句中

循环控制

  1. iteratecontinue
  2. leavebreak

while

先判断,后执行

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

如果要搭配循环控制,要给循环语句起标签名

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

loop

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

loop 没有 循环条件,所以要搭配 循环控制 使用;否则就是死循环

repeat

先执行后判断

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

类比 do ... while ...

案例

eg:批量插入,根据次数插入到 employees 表中多条记录

delimiter $
create procedure pro_while(in insertCount int)
begin
	declare i int default 1; -- 定义局部变量并初始化
	while i <= insertCount do
		insert into `employees`(`eName`, `id`) values(concat('rose', i), '666');
		set i = i + 1; -- 循环变量更新
    end while;
end $

call pro_while(100)$

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

delimiter $
create procedure pro_while(in insertCount int)
begin
	declare i int default 1;
	a: while i <= insertCount do
		insert into `employees`(`eName`, `id`) values(concat('rose', i), '666');
         if i >= 20 then leave a; -- leave 控制语句
         end if;
		set i = i + 1; -- 循环变量更新
    end while a;
end $
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

JS.Huang

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值