顺序结构:程序从上到下依次执行 分支结构:程序从两条或多条路径中选择一条去执行 循环结构:程序在满足一定条件的基础上,重复执行一段代码
功能:实现简单的双分支 语法: select if(表达式,表达式2,表达式3) 执行顺序: 如果表达式1成立,if函数返回表达式2的值,否则返回表达式3的值 应用:任何地方 语法: if 条件1 then 语句1; elseif 条件2 then 语句2; … 【else 语句n;】 end if; 根据传入的乘积,返回等级: create function fun_if(score int) returns char(1) begin if score between 90 and 100 then return “A”; elseif score between 80 and 90 then return “B”; elseif score between 70 and 80 then return “C”; else return “D”; end if; end $ 应用场景:只能应用在begin和and中
情况1:类似于java中的switch与,一般用于实现的等值判断 语法: case 变量|表达式|字段 when 要判断的值 then 返回的值1 when 要判断的值 then 返回的值2 when 要判断的值 then 返回的值3 … else 要返回的值 n end 情况2:类似于java中的多重if语句,一般用于实现区间判断: 语法: case when 要判断的值 then 返回的值1 when 要判断的值 then 返回的值2 when 要判断的值 then 返回的值3 … else 要返回的值 n end case;
特点: 1.可以作为表达式,嵌套在其他语句中使用,可以放在任何地方,可以作为独立的语句去使用. 2.如果when中的值满足或条件成立,则执行对应的then后面的语句,并且结束case,如果都不满足,则执行else中的语句或值 3.else可以省略,如果else省略了,并且所有when条件都不满足,则返回null 创建存储过程,根据传入的成绩来显示等级: create procedure pro_gradle(in score int) begin case when score between 90 and 100 then select “A”; when score between 80 and 90 then select “B”; when score between 60 and 70 then select “C”; else select “D”, end case end $ call pro_gradle(90);
分类:while、loop、repeat 循环控制: iterate类似于continue,结束本次循环,继续上一次 leave类似于break,结束跳出当前循环
先判断后执行 语法: 标签:while 循环条件 do 循环体; end while 标签; 批量插入,根据次数插入到admin表中多条记录: create procedure pro_while1(in insertCount int) begin declare i int default 1; while i<=insertCount do insert into admin(username,password) values(concat(“admin”,i),“admin”); set i=i+1; end while; end $
先执行后判断 语法: 【标签:】loop 循环体; end loop 【标签】 可以用来模拟简单的死循环 添加leave语句: 批量插入,根据次数插入到admin表中多条记录:如果次数大于20就停止: create procedure pro_while2(in insertCount int) begin declare i int default 1; w1:while i<=insertCount do insert into admin(username,password) values(concat(“春”,i),“6666”); if i>=20 then leave w1; end if; set i=i+1; # 之前忘了写条件,往数据库插入了1000多条数据=.= end while w1; end $
没有条件的死循环 语法: 【标签:】repeat 循环体; until 结束循环的条件 end repeat【标签】; 添加iterate语句: 批量插入,根据次数插入到admin表中多条记录,只插入偶数次: create procedure pro_while3(in insertCount int) begin declare i int default 0; w1:while i<=insertCount do set i=i+1; if mod(i,2) !=0 then iterate w1; end if; insert into admin(username,password) values(concat(“春”,i),“6666”); end while w1; end $
向表中插入指定个数的随机字符串: create procedure randstr_insert(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<=insertCount do set len=floor(rand()*(20-startIndex+1)+1); set startIndex=floor(rand()*26+1);# 产生一个随机的整数 insert into stringcontent(content) values(substr(str,startIndex,len)); set i=i+1; end while; end $
~~至此,mysql初级教程完结!