23.流程控制结构

(一)顺序结构

(二)分支结构

1.if函数

功能:实现简单的双分支。

语法:select if(表达式1,表达式2,表达式3);

执行顺序:如果表达式1成立,则if返回表达式2的值,否则返回表达式3的值。

应用:任何地方。

2.case结构

情况1:类似于java中的switch语句,一般用于实现等值判断。

语法:

case 变量|表达式|字段

扫描二维码关注公众号,回复: 8805372 查看本文章

when 要判断的值 then 返回的值1或语句1;

when 要判断的值 then 返回的值2或语句2;

...

else 要返回的值n或语句n

end或end case;

情况2:类似于java中的多重if语句,一般用于实现区间判断。

case

when 要判断的条件1 then 返回的值1或表达式1

when 要判断的条件2 then 返回的值2或表达式2

...

else 要返回的值n或表达式n

end或end case;

特点:

1.如果then返回表达式,嵌套在其他语句中使用,可以放在任何地方begin end中或begin end外。

如果then返回独立的语句,只能放在begin end中。

2.如果when中的值或条件成立,则执行对应的then后面的语句,并且结束case。如果都不满足,执行else中的语句或值。

3.else可以省略,如果else省略了并且所有when条件都不满足,则返回null。

3.if结构

功能:实现多重分支

语法:

if 条件1 then 语句1;

elseif 条件2 语句2;

....

[else 语句n;]

end if;

只能应用在begin end中 

(三)循环结构

循环控制:iterate类似于continue,leave类似于break。

1.while

语法:

[标签:]while 循环条件 do

循环体;

end while [标签];

2.loop

语法:

[标签:]loop

循环体;

end loop [标签];

3.repeat

语法:

[标签:]repeat

循环体;

util 结束循环的条件;

end repeat [标签];

例,已知表stringcontent,其中字段:id 自增长 content varchar(26),向该表插入指定个数的随机字符串。

drop table if exists stringcontent;
create table stringcontent(
	id int primary key auto_increment,
    content varchar(26)
);
drop procedure if exists pro;
delimiter $
create procedure pro(in k int)
begin 
	declare i int default 1;
    declare str varchar(26) default 'abcdefghijklmopqrstuvwxyz';
    declare startIndex int default 1;
    declare len int default 1;
	a:while i<=k do 
		set startIndex=floor(rand()*26+1);
        set len=floor(rand()*(26-startIndex+1)+1);
        insert into stringcontent(content) values(substr(str,startIndex,len));
		set i=i+1;
    end while a; 
end $
call pro(7)$
select * from stringcontent;
发布了90 篇原创文章 · 获赞 48 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Asher_S/article/details/89977636
今日推荐