各位用户为了找寻关于mysql代码执行结构实例分析【顺序、分支、循环结构】的资料费劲了很多周折。这里教程网为您整理了关于mysql代码执行结构实例分析【顺序、分支、循环结构】的相关资料,仅供查阅,以下为您介绍关于mysql代码执行结构实例分析【顺序、分支、循环结构】的详细内容
本文实例讲述了mysql代码执行结构。分享给大家供大家参考,具体如下:
本文内容:
什么是代码执行结构 顺序结构 分支结构 循环结构首发日期:2018-04-18
什么是代码执行结构:
这里所说的代码执行结构就是多条sql语句的执行顺序。 代码执行结构主要用于触发器、存储过程和函数等存储多条sql语句中。顺序结构:
顺序结构就是从上到下依次执行sql语句 一般默认情况下都是顺序结构分支结构:
分支结构的执行是依据一定的条件选择执行路径,它会依据我们给定的条件来选择执行那些sql语句 mysql中分支结构只有if-else: 语法: ? 1 2 3 4 5 6 7if 条件
then
sql语句
[elseif 条件
then
sql语句]
[
else
sql语句]
end
if;
示例:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
--
create
table
pass(id
int
primary
key
auto_increment,
name
varchar
(15),score
int
);
create
table
unpass(id
int
primary
key
auto_increment,
name
varchar
(15),score
int
);
-- 使用存储过程来
create
procedure
myif(
in
name
varchar
(15),
in
score
int
)
begin
if score >=60
then
insert
into
pass(
name
,score)
values
(
name
,score);
else
insert
into
unpass(
name
,score)
values
(
name
,score);
end
if;
end
;
-- 调用,并查看结果
call myif(
"lilei"
,61);
call myif(
"hanmeimei"
,95);
select
*
from
pass;
select
*
from
unpass;
call myif(
"tuhao"
,59);
select
*
from
unpass;
if中的条件基本可以参照select语句的while子句的条件。什么innot in = != 等都可以用。
?
1
2
3
4
5
6
7
8
9
10
11
create
procedure
myif3(
in
a
char
(1))
begin
if a
in
(
'a'
,
'b'
)
then
select
1;
else
select
2;
end
if;
end
;
call myif3(
'a'
);
call myif3(
'b'
);
call myif3(
'c'
);
补充:
理论上,如果做出判断不符合,然而又不想继续执行下去的时候,应该执行返回(比如c语言的return来中断函数运行),但mysql中并没有对应的中断机制,所以需要我们主动中断(中断的方法有很多种,比如执行一条符合语法但无法运行的语句)【这种场景比如有:判断一名学生是否存在,不存在就不执行任何操作,所以应该执行一条无法成功运行的语句来报错返回。】 事实上,还存在一种分支结构:case when 【好像好多书都没怎么讲到,所以这里不讲述。有兴趣的可以自行百度。】循环结构:
循环结构是指在程序中需要反复执行某个功能而设置的一种程序结构。mysql中循环结构用于循环多次运行同一sql语句。 mysql中的循环结构有loop结构、while结构、repeat结构,这里只讲述while结构,有兴趣了解其他的可以自行百度。
while 条件 do
sql语句
end
while;
学过其他语言的可能会了解到循环结构中有continue(提前结束此次循环)和break(跳出整个循环)
在mysql的循环结构中,使用leave来代替break,使用iterate来代替continue,但它们的使用语法是:leaveiterate 循环名,所以如何定义循环名呢?
?
1
2
3
4
循环名:while 条件 do
sql语句;
leaveiterate 循环名;
end
while;
示例:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
-- 无意义的一个例子,仅作演示
create
table
whilenum(id
int
);
-- 自带条件的
create
procedure
mywhile()
begin
declare
num
int
;
set
num=10;
c1:while num>0 do
insert
into
whilenum
values
(num);
set
num=num-1;
end
while;
end
;
-- 以传入参数作为条件的
create
procedure
mywhile2(
in
num
int
)
begin
c1:while num>0 do
insert
into
whilenum
values
(num);
set
num=num-1;
end
while;
end
;
-- 带中断的
create
procedure
mywhile3(
in
num
int
)
begin
c1:while num>0 do
if num%2=0
then
set
num=num-1;
iterate c1;
end
if;
insert
into
whilenum
values
(num);
set
num=num-1;
end
while;
end
;
希望本文所述对大家MySQL数据库计有所帮助。
原文链接:https://www.cnblogs.com/progor/p/8874644.html