一、流程语句讲解
二、总结
一、流程语句讲解
1.1 if语句讲解
语法:
IF condition THENstatements;
ELSEIF condition THENstatements;
ELSEstatements;
END IF;
题目示例:
# 判断成绩等级
# 输入学生的编号,取出学生的第一门课,然后判断当前的课程的等级
drop procedure if exists p2 delimiter $$
create procedure p2(in stuID int)
begin-- 定义局部变量declare myScore double default 0.0;declare myCname varchar(20);-- 查询学生成绩select score,sname into myScore,myCname from v4 where sid = stuIDorder by score desclimit 1;-- 根据局部变量做判断if myScore>80 thenselect concat(myCname,'A') 课程情况;elseif myScore<80 and myScore>60 then select concat(myCname,'B') 课程情况;else select concat(myCname,'C') 课程情况;end if;
end$$
delimiter;call p2(1);注释:
declare 定义局部变量
procedure 存储过程
delimiter 定义结束符
call 调用
concat 将多个字符串连接成一个字符串v4是一个连表视图
1.2 case条件语句
语法:
CASE XWHEN condition1 THEN statements1WHEN condition2 THEN statements2...ELSE statements
END CASE;
题目示例:
-- 查询学生性别,将男女换成小伙子和小姑娘
drop procedure if exists p3;
delimiter $$
create procedure p3(in stuID int)
begin-- 定义局部变量declare mySname varchar(20);declare mySex varchar(20);-- 查询学生性别select sname,ssex into mySname,mySex from v4 where sid = stuId limit 1;-- 根据局部变量做判断case mySex when '男' then set mySex = '小伙子';when '女' thenset mySex = '小姑娘';else set mySex = '妖怪';end case;select mySname,mySex;
end$$
delimiter ;call p3(6);
1.3 LOOP循环语句
语法:
[loop_label:] LOOPstatements;IF condition THENLEAVE [loop_label];END IF;
END LOOP [loop_label];
题目示例:
-- 输出10次Hello World
drop procedure if exists p4;delimiter $$
create procedure p4()
begin -- 定义局部变量declare n int default 0;-- 死循环myloop: loop select 'hello world';set n= n+1;if n >= 10 thenleave myloop;end if;end loop;
end$$
delimiter ;call p4();注释:
leave 停止循环
myloop 给loop循环取别名,用来停止循环
1.4 while循环语句
语法:
[while_label:] WHILE condition DOstatements;
END WHILE [while_label];
题目示例:
-- while使用
drop procedure if exists p5;delimiter $$
create procedure p5()
begin-- 定义局部变量declare n int default 0;declare s int default 0;while n <= 10 do set s = s+n;set n = n+1;end while;select concat('结果是:',s) result;
end$$
delimiter ;call p5();
二、总结
- if(判断多个区间)
- case(单个值的判断)
- loop(死循环)
- while(循环)