MySQL基础—流程控制结构
流程控制结构
顺序结构:程序从上往下依次执行
分支结构:程序从两条或者多条路径中选择一条去执行
循环结构:程序在满足一定条件的基础上,重复执行一段代码
一、分支结构
1、if函数
功能:实现简单的双分支
语法:
if(表达式1,表达式2,表达式3)
执行顺序
如果表达式1成立,则if函数返回表达式2的值,否则将返回表达式3的值
2、case函数
情况1:类似于java中的switch语句,一般用于实现等值判断
语法:
case 变量/表达式/字段
when 要判断的值 then 返回的值1或语句1;
...
else 要返回的值n或语句n;
end/end case;
情况2:类似于java中的多重if语句,一般用于实现区间判断
语法:
case
when 要判断的条件1 then 返回的值1
when 要判断的条件2 then 返回的值2
...
else 要返回的值n
end
特点:
可以作为表达式,嵌套在其他语句中使用,可以放在任何地方,begin end中或begin end外面
可以作为独立的语句去使用,只能放在begin end中
如果when 中的值满足或条件成立,则执行对应的then后面的语句,并且结束case
如果都不满足,则执行else中的语句或值
else可以省略,如果else省略了,并且所有when条件都不满足,则返回null。
举例:
创建存储过程,根据传入的成绩,来显示等级,比如传入成绩:90-100,显示A,80-90,显示B,60-80,显示C,否则显示D
create procedure test(in score int)
begin
case
when score>=90 and score<=100 then select 'A';
when score>=80 then select 'B';
when score>=60 then select 'C';
else select 'D';
end case;
end $
调用
call test(95)$
3、if结构
功能:实现多重分支
语法:
if 条件1 then 语句1;
elseif 条件2 then 语句2;
...
【else 语句n】
end if
应用在begin end中
二、循环结构
分类
while、loop、repeat
循环控制:
iterate 类似于continue 继续,结束本次循环,继续下一次
leave 类似 break,跳出,结束当前循环
1、while
语法:
【标签:】while 循环条件 do
循环体;
end while【标签】;
2、loop
【标签:】loop
循环体;
end loop 【标签】;
可以用来模拟简单的死循环
3、repeat
【标签:】repeat
循环体;
until结束循环的条件
end repeat 【标签】;
案例:批量插入,根据次数插入到admin表中多条记录
create procedure pro_while (in insertcount int)
begin
declare i int default 1;
while i <= insertcount do
insert into admin(username,'password') value(concat('rose',i),'666')
set i = i+1
end while
end $
2、添加leave语句
案例:批量插入,根据次数插入到admin表中多天记录,如果次数>20则停止
truncate table admin$
drop procedure test_while$
create procedure test_while(in insertcount int)
begin
declare i int default 1;
a:while i<= insertcount do
insert into admin(username,'password')values(concat('xiaohua',i),'0000');
if i >20 then leave a;
end if;
set i = i+1;
end while a;
end $
3、添加iterate语句
truncate table admin$
drop procedure test_while$
create procedure test_while(in insertcount int)
begin
declare i int default 0;
a:while i<= insertcount do
set i = i+1
if mod(i,2)!=0 then itrate a;
end if;
insert into admin(username,'password')values(concat('xiaohua',i),'0000');
end while a;
end $
经典案例:
已知表stringcontent
其中字段:
id 自增长 content varchar(20)
要求:向该表插入指定个数的随机字符串
drop table if exists stringcontent;
create table stringcontent(
id int primary key auto_increament,
content varchar(20)
);
delimiter $
create procedure testranderinsert(in insertcount int)
begin
declare i int default 1;定义一个循环变量,表示插入次数
declare str varchar(26) default 'abcdefghijklmnopqrstuvwxyz';
declare startindex int default 1;
declare len int default 1;
while i <= insertcoindexunt
set len=floor(rand()*(20-startindex+1)+1);产生一个随机的数,代表截取长度,1-(26-startindex+1)+1
set startindex = floor(rand()*26+1)产生一个随机整体,代表起始位置索引1-26
insert into stringcontent(content) vaule(substr(str,startindex,len));
set i = i+1;循环变量更新
end while
end$
浙公网安备 33010602011771号