mysql的判断语句方式
作者:无语堵上西楼
本文详细介绍了SQL中的条件判断(if...else...elseif...)、循环控制(while、repeat、loop)以及它们的使用方法和案例,涵盖了SQL编程中的基本控制结构,对初学者和已有一定基础的开发者都具有一定的参考价值
if
if 用于做条件判断,具体的语法结构如下,在if条件判断的结构中,ELSE IF 结构可以有多个,也可以没有。
ELSE结构可以有,也可以没有。
IF 条件1 THEN ..... ELSEIF 条件2 THEN -- 可选 ..... ELSE -- 可选 ..... END IF;
案例
create procedure p3()
begin
declare score int default 58;
declare result varchar(10);
if score >= 85 then
set result := '优秀';
elseif score >= 60 then
set result := '及格';
else
set result := '不及格';
end if;
select result;
end;
call p3();case
如果判定条件有多个,多个条件之间,可以使用 and 或 or 进行连接。
方法一
-- 含义: 当case_value的值为 when_value1时,执行statement_list1,当值为 when_value2时, 执行statement_list2, 否则就执行 statement_list CASE case_value WHEN when_value1 THEN statement_list1 [ WHEN when_value2 THEN statement_list2] ... [ ELSE statement_list ] END CASE;
方法二
-- 含义: 当条件search_condition1成立时,执行statement_list1,当条件search_condition2成 立时,执行statement_list2, 否则就执行 statement_list CASE WHEN search_condition1 THEN statement_list1 [WHEN search_condition2 THEN statement_list2] ... [ELSE statement_list] END CASE;
案例
create procedure p6(in month int)
begin
declare result varchar(16);
case
when month >= 1 and month <= 3 then
set result := '第一季度';
when month >= 4 and month <= 6 then
set result := '第二季度';
when month >= 7 and month <= 9 then
set result := '第三季度';
when month >= 10 and month <= 12 then
set result := '第四季度';
else
set result := '非法参数';
end case ;
select concat('您输入的月份为: ',month, ', 所属的季度为: ',result);
end;
call p6(16);while
while 循环是有条件的循环控制语句。满足条件后,再执行循环体中的SQL语句。
-- 先判定条件,如果条件为true,则执行逻辑,否则,不执行逻辑
WHILE 条件 DO
SQL逻辑...
END WHILE;案例
-- A. 定义局部变量, 记录累加之后的值; -- B. 每循环一次, 就会对n进行减1 , 如果n减到0, 则退出循环 create procedure p7(in n int) begin declare total int default 0; while n>0 do set total := total + n; set n := n - 1; end while; select total; end; call p7(100);
repeat
repeat是有条件的循环控制语句, 当满足until声明的条件的时候,则退出循环
-- 先执行一次逻辑,然后判定UNTIL条件是否满足,如果满足,则退出。如果不满足,则继续下一次循环
REPEAT
SQL逻辑...
UNTIL 条件
END REPEAT;案例
-- A. 定义局部变量, 记录累加之后的值; -- B. 每循环一次, 就会对n进行-1 , 如果n减到0, 则退出循环 create procedure p8(in n int) begin declare total int default 0; repeat set total := total + n; set n := n - 1; until n <= 0 end repeat; select total; end; call p8(10); call p8(100);
loop
LOOP 实现简单的循环,如果不在SQL逻辑中增加退出循环的条件,可以用其来实现简单的死循环。
LOOP可以配合一下两个语句使用:
- LEAVE :配合循环使用,退出循环。
- ITERATE:必须用在循环中,作用是跳过当前循环剩下的语句,直接进入下一次循环。
[begin_label:] LOOP
SQL逻辑...
END LOOP [end_label];
LEAVE label; -- 退出指定标记的循环体
ITERATE label; -- 直接进入下一次循环案例
-- A. 定义局部变量, 记录累加之后的值; -- B. 每循环一次, 就会对n进行-1 , 如果n减到0, 则退出循环 ----> leave xx create procedure p9(in n int) begin declare total int default 0; sum:loop if n<=0 then leave sum; end if; set total := total + n; set n := n - 1; end loop sum; select total; end; call p9(100);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
