顺序结构:程序从上往下依次执行
分支结构: 程序从两条或多条路径中选择一条去执行
循环结构:程序在满足一定条件的基础上,重复执行一段代码
分支结构
if 函数
实现简单的双分支
语法
if(表达式1,表达式2,表达式3)
执行顺序:
如果表达式1成立,则if函数返回表达式2的值,否则返回表达式3的值
case结构
1.类似于java中的switch语句,一般用于实现的等值判断
语句:
case 变量| 表达式|字段
when 要判断的值 then 返回的值
when 要判断的值 then返回的值
。。。。
else 要返回的值n
end
case 变量| 表达式|字段
when 要判断的值 then 返回的值 或语句1;
when 要判断的值 then返回的值 或语句2;
。。。。
else 要返回的值n 或语句n;
end case;
2.类似于java中的多重if语句,一般用于实现区间判断
语句:
和上面一样
case
when 要判断的条件1 then 返回的值1
when 要判断的条件2 then 返回的值2
。。。
else 要返回的值n
end case
-- 语句中使用case结构
create procedure test_grade_case(IN score int)
begin
select
case
when score BETWEEN 90 and 100 then 'A'
when score BETWEEN 80 and 90 then 'B'
else 'C'
end;
end
call test_grade_case(80);
-- 存储过程中使用case表达式
create procedure test_grade_case2(IN score int)
begin
case
when score >=90 and score<=100 then select 'A';
when score >= 80 then select 'B';
else select 'C';
end case;
end
call test_grade_case2(70);
if结构
功能:实现多重分支
语法:
if 条件1 then 语句1;
elseif 条件2 then 语句2;
。。。。
[else 语句n];—— 可选
end if;
create function test_if_case(score int) returns VARCHAR(20)
begin
if (score >=90 and score <=100) then return 'A';
elseif score >80 then return 'B';
else return 'C';
end if;
END;
select test_if_case(88);
循环结构
-- 插入5条数据
create procedure pro_while(IN insertCount INT)
BEGIN
DECLARE i int default 1;
while i < insertCount do
insert into admin(username,`password`) values(i,i);
set i = i+1;
end while;
END
call pro_while(5);
--- 设计concat相关
drop procedure pro_while;
create procedure pro_while(IN insertCount INT)
BEGIN
DECLARE i int default 1;
while i < insertCount do
insert into admin(username,`password`) values(concat("rose",i),i);
set i = i+1;
end while;
END
call pro_while(5);
--- 添加20 条数据,如果到达20条,退出
drop procedure pro_while;
create procedure pro_while(IN insertCount INT)
BEGIN
DECLARE i int default 1;
a:while i < insertCount do
insert into admin(username,`password`) values(concat("rose",i),i);
-- if 需要end if来结束
if i>=20 then leave a;
end if;
set i = i+1;
end while a;
END
call pro_while(100);
-- 偶数插入
drop procedure pro_while;
create procedure pro_while(IN insertCount INT)
BEGIN
DECLARE i int default 1;
a:while i < insertCount do
set i = i+1;
if mod(i,2)!=0 then iterate a;
end if;
insert into admin(username,`password`) values(concat("rose",i),i);
end while a;
END
call pro_while(100);