diff --git "a/43 \351\237\251\346\226\207\346\235\260/\345\210\206\346\224\257\347\273\223\346\236\204\344\271\213if\345\222\214case\357\274\210\344\275\234\344\270\232\357\274\211.md" "b/43 \351\237\251\346\226\207\346\235\260/\345\210\206\346\224\257\347\273\223\346\236\204\344\271\213if\345\222\214case\357\274\210\344\275\234\344\270\232\357\274\211.md" new file mode 100644 index 0000000000000000000000000000000000000000..0accb7a6fa49a3b316c7e83d2ac5b8380822d879 --- /dev/null +++ "b/43 \351\237\251\346\226\207\346\235\260/\345\210\206\346\224\257\347\273\223\346\236\204\344\271\213if\345\222\214case\357\274\210\344\275\234\344\270\232\357\274\211.md" @@ -0,0 +1,160 @@ + + + + +# 分支结构之 if 和 case 笔记 + +~~~mysql + +(1)分支结构之 IF + +IF 表达式1 THEN 操作1 sql语句 +[ELSEIF 表达式2 THEN 操作2]…… +[ELSE 操作N] +END IF + +特点:① 不同的表达式对应不同的操作 ② 使用在begin end中 + + + + + +(2) 分支结构之 CASE + + 情况1 + +CASE 表达式 +WHEN 值1 THEN 结果1或语句1(如果是语句,需要加分号) +WHEN 值2 THEN 结果2或语句2(如果是语句,需要加分号) +... +ELSE 结果n或语句n(如果是语句,需要加分号) +END [case](如果是放在begin end中需要加上case,如果放在select后面不需要) + + + + 情况2 + +CASE +WHEN 条件1 THEN 结果1或语句1(如果是语句,需要加分号) +WHEN 条件2 THEN 结果2或语句2(如果是语句,需要加分号) +... +ELSE 结果n或语句n(如果是语句,需要加分号) +END [case](如果是放在begin end中需要加上case,如果放在select后面不需要) + + + + + +(3) 循环结构之LOOP + +[loop_label:] LOOP +循环执行的语句 +END LOOP [loop_label] + + + + + +(4) 循环结构之WHILE + + + +[while_label:] WHILE 循环条件 DO +循环体 +END WHILE [while_label]; +~~~ + + + + + + + + + +# 分支结构之 if 和 case 作业 + +~~~mysql + +CREATE database shujuku charset utf8; +use shujuku; + +-#1. 创建函数test_if_case(),实现传入成绩,如果成绩>90,返回A,如果成绩>80,返回B,如果成绩>60,返回C,否则返回D +#要求:分别使用if结构和case结构实现 + +#方式1:if + +delimiter // +CREATE procedure test_if_case(in score DOUBLE(4,1)) +begin + if score>90 then SELECT 'A'; + ELSEIF score>80 then SELECT 'B'; + elseif score>60 then SELECT 'C'; + else SELECT 'D'; + end if ; +END // +delimiter ; + +call test_if_case(89) +#方式2:case when ... +drop procedure test_if_case ; +delimiter // +CREATE procedure test_if_case(in score DOUBLE(4,1)) +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 // +delimiter ; + +call test_if_case(89) + + +#2. 创建存储过程test_if_pro(),传入工资值,如果工资值<3000,则删除工资为此值的员工, +# 如果3000 <= 工资值 <= 5000,则修改此工资值的员工薪资涨1000,否则涨工资500 + + +# 第一种 if 做法 + +delimiter // + +CREATE procedure test_if_pro(in mysalary int) +begin +if mysalary<3000 then drop empname from emp where salary = mysalary ; +ELSEIF 3000 <= mysalary <= 5000 then update emp set salary =mysalary+1000; +else update emp set salary= mysalary +500; +end if ; + +end// + +delimiter; + +call test_if_pro(4562) + + +# 第二种 case 做法 + +delimiter // + +CREATE procedure test_if_pro(in mysalary int) +begin +case +when mysalary<3000 then drop empname from emp where salary = mysalary ; +when 3000 <= mysalary <= 5000 then update emp set salary =mysalary+1000; +else update emp set salary= mysalary +500; +end case ; + +end// + +delimiter; + +call test_if_pro(4562) + + + + +~~~ +