diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231008 if\343\200\201case\343\200\201loop.md" "b/03 \350\265\226\345\277\203\345\246\215/20231008 if\343\200\201case\343\200\201loop.md" new file mode 100644 index 0000000000000000000000000000000000000000..5cadd547dc127d23d86913e707aadfb7269be17b --- /dev/null +++ "b/03 \350\265\226\345\277\203\345\246\215/20231008 if\343\200\201case\343\200\201loop.md" @@ -0,0 +1,146 @@ +## if、case、loop、while + +### if 结构 + +不可以写在select …… from 的……里 + +要加分号; + +```mysql +if 表达式1 then 操作1 sql语句 +elseif 表达式2 then 操作2 +…… +else 操作n +end if +``` + +### case 结构 + +可以写在select …… from 的……里 + +要加分号; + +```mysql +case 表达式(switch形式要表达式,if形式不需要表达式) +when 值1 then 结果1或语句1(如果是语句,需要加分号) +when 值2 then 结果2或语句2(如果是语句,需要加分号) +... +else 结果n或语句n(如果是语句,需要加分号) +end [case](如果是放在begin end中需要加上case,如果放在select后面不需要) +``` + +### loop 循环 + +```mysql +循环名: loop +循环执行的语句 +end loop 循环名 +``` + +输出1-num之间的偶数 + +```mysql +declare i int default 1 -- 起始变量 i=1 +a:loop + if i%2=0 then select i; + end if; + set i=i+1; + if i=num then leave a; -- leava a 则是退出循环 + end if; + set i=i+1; +end loop a; +``` + +累加 + +```mysql +b:loop + if i>num then leave b; + end if; + set sum=sum+i; + set i=i+1; +end loop b; +``` + +### while 循环 + +输出1-10 + +```mysql +declare i int default 1; +while i<=10 do + select i; + set i=i+1; +end while; +``` + +累加 + +```mysql +declare i int default 1; +declare sum int default 0; +while i<= num do + set sum=sum+i; + i=i+1; +end while; +select sum +``` + + + +## 练习 + +```mysql +create database a charset utf8; + +use a; + +-#1. 创建函数test_if_case(),实现传入成绩,如果成绩>90,返回A,如果成绩>80,返回B,如果成绩>60,返回C,否则返回D +#要求:分别使用if结构和case结构实现 + +#方式1:if +delimiter // + create procedure test_if(in num double(3,1),out res varchar(10)) + begin + if num<0 then select '输出错误' into res; + elseif num>90 then select 'A' into res; + elseif num>80 then select 'B' into res; + elseif num>60 then select 'C' into res; + else select 'D' into res; + end if; + end // + +call test_if(90,@res); + +select @res; +#方式2:case when ... +delimiter // + create procedure test_case(in num int) + begin + case + when num<0 then select '输入错误'; + when num>90 then select 'A' ; + when num>80 then select 'B' ; + when num>60 then select 'C' ; + else select 'D'; + end case; + end // + +call test_case(80); +#2. 创建存储过程test_if_pro(),传入工资值,如果工资值<3000,则删除工资为此值的员工, +# 如果3000 <= 工资值 <= 5000,则修改此工资值的员工薪资涨1000,否则涨工资500 +delimiter // + create procedure test_if_pro(in sal int) + begin + if sal<3000 then + delete from employees where salary=sal; + elseif 3000<=sal and sal<=5000 then + update employees set salary=salary+1000 where salary=sal; + else + update employees set salary=salary+500 where salary=sal; + end if; + end // + +call test_if_pro(3200); +``` +