mysql系列XI-存储过程

存储过程是事先经过编译并存储在数据库中的一段 SQL 语句的集合,调用存储过程可以简化应用开发人员的很多工作,减少数据在数据库和应用服务器之间的传输,对于提高数据处理的效率是有好处的。

存储过程思想上很简单,就是数据库 SQL 语言层面的代码封装与重用。

特点:

  • 封装复用 : 可以把某一业务SQL封装在存储过程中,需要用到的时候直接调用即可。
  • 可以接收参数,也可以返回数据:再存储过程中,可以传递参数,也可以接收返回值。
  • 减少网络交互,效率提升: 如果涉及到多条SQL,每执行一次都是一次网络传输。 而如果封装在存储过程中,我们只需要网络交互一次可能就可以了。

基本语法

创建

1
2
3
4
CREATE PROCEDURE 存储过程名称 ([ 参数列表 ])
BEGIN
-- SQL语句
END ;

调用

1
CALL 名称 ([ 参数 ]);

查看

1
2
3
4
5
-- 查询指定数据库的存储过程及状态信息
SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = 'xxx';

-- 查询某个存储过程的定义
SHOW CREATE PROCEDURE 存储过程名称;

删除

1
DROP PROCEDURE [ IF EXISTS ] 存储过程名称;

注意:
在命令行中,执行创建存储过程的SQL时,需要通过关键字 delimiter 指定SQL语句的结束符。

示例

创建存储过程
1
2
3
4
5
6
7
8
9
-- 存储过程p1存在则先删除该存储过程
DROP PROCEDURE IF EXISTS p1;

-- 创建存储过程p1
CREATE PROCEDURE p1()
BEGIN
-- 查询tb_user总数
SELECT count(*) as sums FROM tb_user;
END
调用存储过程
1
2
3
4
5
6
7
8
9
mysql> call p1();
+------+
| sums |
+------+
| 24 |
+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)
查看studydata所有存储过程
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
33
34
35
36
37
38
39
40
41
42
43
mysql> select * from information_schema.ROUTINES where ROUTINE_SCHEMA = 'studydata' \G;
*************************** 1. row ***************************
SPECIFIC_NAME: p1
ROUTINE_CATALOG: def
ROUTINE_SCHEMA: studydata
ROUTINE_NAME: p1
ROUTINE_TYPE: PROCEDURE
DATA_TYPE:
CHARACTER_MAXIMUM_LENGTH: NULL
CHARACTER_OCTET_LENGTH: NULL
NUMERIC_PRECISION: NULL
NUMERIC_SCALE: NULL
DATETIME_PRECISION: NULL
CHARACTER_SET_NAME: NULL
COLLATION_NAME: NULL
DTD_IDENTIFIER: NULL
ROUTINE_BODY: SQL
ROUTINE_DEFINITION: BEGIN
SELECT
count( * ) as sums
FROM
tb_user;

END
EXTERNAL_NAME: NULL
EXTERNAL_LANGUAGE: SQL
PARAMETER_STYLE: SQL
IS_DETERMINISTIC: NO
SQL_DATA_ACCESS: CONTAINS SQL
SQL_PATH: NULL
SECURITY_TYPE: DEFINER
CREATED: 2022-08-05 18:39:28
LAST_ALTERED: 2022-08-05 18:39:28
SQL_MODE: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
ROUTINE_COMMENT:
DEFINER: root@localhost
CHARACTER_SET_CLIENT: utf8mb4
COLLATION_CONNECTION: utf8mb4_0900_ai_ci
DATABASE_COLLATION: utf8mb4_0900_ai_ci
1 row in set (0.00 sec)

ERROR:
No query specified
查看指定存储过程的定义
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mysql> show create procedure p1 \G;
*************************** 1. row ***************************
Procedure: p1
sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
Create Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `p1`( )
BEGIN
SELECT
count( * ) as sums
FROM
tb_user;

END
character_set_client: utf8mb4
collation_connection: utf8mb4_0900_ai_ci
Database Collation: utf8mb4_0900_ai_ci
1 row in set (0.00 sec)

ERROR:
No query specified
删除指定存储过程
1
2
mysql> drop procedure if exists p1;
Query OK, 0 rows affected (0.01 sec)

变量

在MySQL中变量分为三种类型: 系统变量、用户定义变量、局部变量。

系统变量

系统变量 是MySQL服务器提供,不是用户定义的,属于服务器层面。分为全局变量(GLOBAL)、会话变量(SESSION)。

查看系统变量
1
2
3
4
5
6
7
8
-- 查看所有系统变量
SHOW [ SESSION | GLOBAL ] VARIABLES ;

-- 可以通过LIKE模糊匹配方式查找变量
SHOW [ SESSION | GLOBAL ] VARIABLES LIKE '......';

-- 查看指定变量的值
SELECT @@[SESSION | GLOBAL] 系统变量名;
设置系统变量
1
2
SET [ SESSION | GLOBAL ] 系统变量名 = 值 ;
SET @@[SESSION | GLOBAL]系统变量名 = 值 ;

注意:
如果没有指定SESSION/GLOBAL,默认是SESSION,会话变量。
A. 全局变量(GLOBAL): 全局变量针对于所有的会话。
B. 会话变量(SESSION): 会话变量针对于单个会话,在另外一个会话窗口就不生效了。

演示示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-- 查看系统变量
show session variables ;
show session variables like 'auto%';
show global variables like 'auto%';
select @@global.autocommit;
select @@session.autocommit;

-- 设置系统变量
set session autocommit = 1;
-- 关闭自动提交后,如果重启mysql服务,还会变为开启状态
set global autocommit = 0;

-- 如果关闭事务自动提交,每次执行必须手动commit才能提交
insert into user(id, name) VALUES (6, '张大三');
select @@global.autocommit;

用户定义变量

用户定义变量 是用户根据需要自己定义的变量,用户变量不用提前声明,在用的时候直接用 “@变量名” 使用就可以。其作用域为当前连接。

赋值

方式一:

1
2
SET @var_name = expr [, @var_name = expr] ... ;
SET @var_name := expr [, @var_name := expr] ... ;

赋值时,可以使用 = ,也可以使用 := 。

方式二:

1
2
SELECT @var_name := expr [, @var_name := expr] ... ;
SELECT 字段名 INTO @var_name FROM 表名;
使用
1
SELECT @var_name ;

注意: 用户定义的变量无需对其进行声明或初始化,只不过获取到的值为NULL。

演示示例
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
-- 赋值

mysql> set @uname = '张三';
Query OK, 0 rows affected (0.00 sec)

mysql> set @uage := 18;
Query OK, 0 rows affected (0.00 sec)

mysql> set @ugender := '男', @uhobby := 'Python';
Query OK, 0 rows affected (0.00 sec)

-- 使用select赋值,会有查询结果返回
mysql> select @ucolor := 'red';
+------------------+
| @ucolor := 'red' |
+------------------+
| red |
+------------------+
1 row in set, 1 warning (0.00 sec)

mysql> select count(*) into @ucount from tb_user;
Query OK, 1 row affected (0.01 sec)


-- 查询使用用户定义变量

mysql> select @uname, @uage, @ugender, @uhobby;
+--------+-------+----------+---------+
| @uname | @uage | @ugender | @uhobby |
+--------+-------+----------+---------+
| 张三 | 18 | 男 | Python |
+--------+-------+----------+---------+
1 row in set (0.00 sec)

mysql> select @ucolor, @ucount;
+---------+---------+
| @ucolor | @ucount |
+---------+---------+
| red | 24 |
+---------+---------+
1 row in set (0.00 sec)

mysql> select @sdfadf;
+------------------+
| @sdfadf |
+------------------+
| NULL |
+------------------+
1 row in set (0.00 sec)

局部变量

局部变量 是根据需要定义的在局部生效的变量,访问之前,需要DECLARE声明。可用作存储过程内的局部变量和输入参数,局部变量的范围是在其内声明的BEGIN … END块。

声明
1
DECLARE 变量名 变量类型 [DEFAULT ... ] ;

变量类型就是数据库字段类型:INT、BIGINT、CHAR、VARCHAR、DATE、TIME等。

赋值
1
2
3
SET 变量名 = 值 ;
SET 变量名 := 值 ;
SELECT 字段名 INTO 变量名 FROM 表名 ... ;
演示示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-- 声明局部变量 - declare
-- 赋值

drop procedure if exists p1;
create procedure p1()
begin
declare user_total int default 0;
select count(*) into user_total from tb_user;
select user_total;
end;


mysql> call p1();
+------------+
| user_total |
+------------+
| 24 |
+------------+
1 row in set (0.01 sec)

if

介绍

if 用于做条件判断,具体的语法结构为:

1
2
3
4
5
6
7
IF 条件1 THEN
.....
ELSEIF 条件2 THEN -- 可选
.....
ELSE -- 可选
.....
END IF;

在if条件判断的结构中,ELSE IF 结构可以有多个,也可以没有。 ELSE结构可以有,也可以没有。

案例

根据定义的工资salary变量,判定当前工资对应的工资等级。
salary >= 10000,等级为高薪。
salary >= 5000 且 salary < 10000,等级为普通薪资。
salary< 5000 ,等级为低薪。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
drop procedure if exists p1;
create procedure p1()
begin
declare salary int default 4999;
declare result varchar(20);
if salary>=10000 then
set result := '高薪';
elseif salary >= 5000 and salary < 10000 then
set result := '普通薪资';
else
set result := '低薪';
end if;
select result;
end;

mysql> call p1();
+--------+
| result |
+--------+
| 低薪 |
+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

上述的需求我们虽然已经实现了,但是也存在一些问题,比如:salary工资我们是在存储过程中定义死的,而且最终计算出来的薪水等级,我们也仅仅是最终查询展示出来而已。

那么我们能不能,把salary工资动态的传递进来,计算出来的薪水等级是否可以作为返回值返回呢?
答案是肯定的,我们可以通过接下来所讲解的 参数 来解决上述的问题。

参数

介绍

参数的类型,主要分为以下三种:INOUTINOUT。 具体的含义如下:

类型含义备注
IN该类参数作为输入,也就是需要调用时传入值默认
OUT该类参数作为输出,也就是该参数可以作为返回值
INOUT既可以作为输入参数,也可以作为输出参数

用法

1
2
3
4
CREATE PROCEDURE 存储过程名称 ([ IN/OUT/INOUT 参数名 参数类型 ])
BEGIN
-- SQL语句
END ;

案例

案例1

根据传入的参数salary,判定当前工资对应的薪水等级, 并返回。
salary >= 10000,等级为高薪。
salary >= 5000 且 salary < 10000,等级为普通薪资。
salary< 5000 ,等级为低薪。

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
33
34
35
drop procedure if exists p1;
create procedure p1(in salary int, out result varchar(20))
begin
if salary >= 10000 then
set result := '高薪';
elseif salary >= 5000 and salary < 10000 then
set result := '普通薪资';
else
set result := '低薪';
end if;
end;

-- 定义用户变量 @res, 用户变量可以不用声明
mysql> call p1(5267, @res);
Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+----------+
| @res |
+----------+
| 普通薪资 |
+----------+
1 row in set (0.00 sec)

-- 定义用户变量 @res, 用户变量可以不用声明
mysql> call p1(41525, @res);
Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+------+
| @res |
+------+
| 高薪 |
+------+
1 row in set (0.00 sec)

案例2
将传入的税前薪资,进行换算,扣除个人五险一金(17%)后剩余的到手部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
drop procedure if exists p1;
create procedure p1(inout salary int)
begin
set salary := salary - salary*0.17;
end


mysql> set @salary := 10000;
Query OK, 0 rows affected (0.00 sec)

mysql> call p1(@salary);
Query OK, 0 rows affected (0.00 sec)

mysql> select @salary;
+---------+
| @salary |
+---------+
| 8300 |
+---------+
1 row in set (0.00 sec)

case

介绍

case结构及作用,和我们在基础篇中所讲解的流程控制函数很类似。有两种语法格式:

语法1:

1
2
3
4
5
6
-- 含义: 当case_value的值为 when_value1时,执行statement_list1,当值为 when_value2时,执行statement_list2, 否则就执行 statement_list
CASE case_value
WHEN when_value1 THEN statement_list1
[ WHEN when_value2 THEN statement_list2] ...
[ ELSE statement_list ]
END CASE;

语法2:

1
2
3
4
5
6
-- 含义: 当条件search_condition1成立时,执行statement_list1,当条件search_condition2成立时,执行statement_list2, 否则就执行 statement_list
CASE
WHEN search_condition1 THEN statement_list1
[WHEN search_condition2 THEN statement_list2] ...
[ELSE statement_list]
END CASE;

案例

根据传入的月份,判定月份所属的季节(要求采用case结构)。
1-3月份,为第一季度
4-6月份,为第二季度
7-9月份,为第三季度
10-12月份,为第四季度

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
33
34
35
36
37
38
39
40
41
42
43
44
45
drop procedure if exists p1;
create procedure p1(in now_month int, out result varchar(20))
begin
case
when now_month>=1 and now_month<4 then
set result := '第一季度';
when now_month >=4 and now_month<7 then
set result := '第二季度';
when now_month >=7 and now_month<10 then
set result := '第三季度';
when now_month >=10 and now_month <13 then
set result := '第四季度';
else set result :='输入月份有误';
end case;
end;



mysql> set @m := 11;
Query OK, 0 rows affected (0.00 sec)

mysql> call p1(@m, @res);
Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+----------+
| @res |
+----------+
| 第四季度 |
+----------+
1 row in set (0.00 sec)

mysql> set @m := 20;
Query OK, 0 rows affected (0.00 sec)

mysql> call p1(@m, @res);
Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+--------------+
| @res |
+--------------+
| 输入月份有误 |
+--------------+
1 row in set (0.00 sec)

注意:如果判定条件有多个,多个条件之间,可以使用 and 或 or 进行连接。

while

介绍

while 循环是有条件的循环控制语句。满足条件后,再执行循环体中的SQL语句。具体语法为:

1
2
3
4
-- 先判定条件,如果条件为true,则执行逻辑,否则,不执行逻辑
WHILE 条件 DO
SQL逻辑...
END WHILE;

案例

计算从1累加到n的值,n为传入的参数值。

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
drop procedure if exists p1;
create procedure p1(inout n int)
begin
declare total int default 0;
while n>0 do
set total := total + n;
set n := n-1;
end while;
set n := total;
end


mysql> set @r:=100;
Query OK, 0 rows affected (0.00 sec)

mysql> call p1(@r);
Query OK, 0 rows affected (0.00 sec)

mysql> select @r;
+------+
| @r |
+------+
| 5050 |
+------+
1 row in set (0.00 sec)

repeat

介绍

repeat是有条件的循环控制语句, 当满足until声明的条件的时候,则退出循环 。具体语法为:

1
2
3
4
5
-- 先执行一次逻辑,然后判定UNTIL条件是否满足,如果满足,则退出。如果不满足,则继续下一次循环
REPEAT
SQL逻辑...
UNTIL 条件
END REPEAT;

案例

计算从1累加到n的值,n为传入的参数值。(使用repeat实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
drop procedure if exists p1;
create procedure p1(in n int, out total int)
begin
set total := 0;
repeat
set total := total + n;
set n := n - 1;
until n <1
end repeat;
end;


mysql> call p1(10, @res);
Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+------+
| @res |
+------+
| 55 |
+------+
1 row in set (0.00 sec)

loop

介绍

LOOP 实现简单的循环,如果不在SQL逻辑中增加退出循环的条件,可以用其来实现简单的死循环。
LOOP可以配合一下两个语句使用:

  • LEAVE :配合循环使用,退出循环。
  • ITERATE:必须用在循环中,作用是跳过当前循环剩下的语句,直接进入下一次循环。
1
2
3
[begin_label:] LOOP
SQL逻辑...
END LOOP [end_label];
1
2
LEAVE label; -- 退出指定标记的循环体
ITERATE label; -- 直接进入下一次循环

上述语法中出现的 begin_label,end_label,label 指的都是我们所自定义的标记。

案例

案例一
计算从1累加到n的值,n为传入的参数值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
drop procedure if exists p1;
create procedure p1(in n int, out res int)
begin
set res := 0 ;
get_sum: loop
if n<1 then
leave get_sum;
end if;
set res := res+n;
set n := n-1;
end loop get_sum;
end;


mysql> select @res;
+------+
| @res |
+------+
| 55 |
+------+
1 row in set (0.00 sec)

案例二
计算从1到n之间的偶数累加的值,n为传入的参数值。

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
drop procedure if exists p1;
create procedure p1(in n int, out total int)
begin
set total := 0;
get_sum:loop
if n<1 then
leave get_sum;
end if;
if n%2=1 then
set n := n - 1;
iterate get_sum;
end if;
set total := total + n;
set n := n - 1;
end loop get_sum;
end;


mysql> call p1(10, @res);
Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+------+
| @res |
+------+
| 30 |
+------+
1 row in set (0.00 sec)

if n%2=1 then一定注意这行代码,其他编程语言里判断值相等都会用==,mysql里使用了=作为判断值的表达式,所以也建议给变量赋值时尽量使用:=,而不要使用=,以免造成混肴。

这个案例另外一个要注意的还是这条语句,这条语句我们原本想表达意思是如果是奇数,我们就跳过本次循环,继续进行下次循环,所以n的值也是要减1的,且不要忘了直接只跳过了本次循环,这样造成了死循环。

游标

介绍

游标(CURSOR)是用来存储查询结果集的数据类型 , 在存储过程和函数中可以使用游标对结果集进行循环的处理。游标的使用包括游标的声明、OPEN、FETCH 和 CLOSE,其语法分别如下。

声明游标

1
DECLARE 游标名称 CURSOR FOR 查询语句 ;

打开游标

1
OPEN 游标名称 ;

获取游标记录

1
FETCH 游标名称 INTO 变量 [, 变量 ] ;

关闭游标

1
CLOSE 游标名称 ;

案例

根据传入的参数uage,来查询用户表tb_user中,所有的用户年龄小于等于uage的用户姓名(name)和专业(profession),并将用户的姓名和专业插入到所创建的一张新表(id,name,profession)中。

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
-- 逻辑:
-- A. 声明游标, 存储查询结果集
-- B. 准备: 创建表结构
-- C. 开启游标
-- D. 获取游标中的记录
-- E. 插入数据到新表中
-- F. 关闭游标
create procedure p1(in uage int)
begin
declare uname varchar(100);
declare upro varchar(100);
declare u_cursor cursor for select name,profession from tb_user where age <= uage;
drop table if exists tb_user_pro;
create table if not exists tb_user_pro(
id int primary key auto_increment,
name varchar(100),
profession varchar(100)
);
open u_cursor;
while true do
fetch u_cursor into uname,upro;
insert into tb_user_pro values (null, uname, upro);
end while;
close u_cursor;
end;

上述的存储过程,最终我们在调用的过程中,会报错,之所以报错是因为上面的while循环中,并没有退出条件。当游标的数据集获取完毕之后,再次获取数据,就会报错,从而终止了程序的执行。

1
2
mysql> call p1(30);
ERROR 1329 (02000): No data - zero rows fetched, selected, or processed

但是此时,tb_user_pro表结构及其数据都已经插入成功了,我们可以直接刷新表结构,检查表结构中的数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mysql> select * from tb_user_pro;
+----+--------+--------------------+
| id | name | profession |
+----+--------+--------------------+
| 1 | 吕布 | 软件工程 |
| 2 | 花木兰 | 软件工程 |
| 3 | 大乔 | 舞蹈 |
| 4 | 露娜 | 应用数学 |
| 5 | 白起 | 机械工程及其自动化 |
| 6 | 韩信 | 无机非金属材料工程 |
| 7 | 荆轲 | 会计 |
| 8 | 狄仁杰 | 国际贸易 |
| 9 | 廉颇 | 土木工程 |
| 10 | 后羿 | 城市园林 |
| 11 | 姜子牙 | 工程造价 |
+----+--------+--------------------+
11 rows in set (0.00 sec)

上述的功能,虽然我们实现了,但是逻辑并不完善,而且程序执行完毕,获取不到数据,数据库还报错。 接下来,我们就需要来完成这个存储过程,并且解决这个问题。
要想解决这个问题,就需要通过MySQL中提供的 条件处理程序 Handler 来解决。

条件处理程序

介绍

条件处理程序(Handler)可以用来定义在流程控制结构执行过程中遇到问题时相应的处理步骤。具体语法为:

1
2
3
4
5
6
7
8
9
DECLARE handler_action HANDLER FOR condition_value [, condition_value]... statement ;
handler_action 的取值:
CONTINUE: 继续执行当前程序
EXIT: 终止执行当前程序
condition_value 的取值:
SQLSTATE sqlstate_value: 状态码,如 02000
SQLWARNING: 所有以01开头的SQLSTATE代码的简写
NOT FOUND: 所有以02开头的SQLSTATE代码的简写
SQLEXCEPTION: 所有没有被SQLWARNING 或 NOT FOUND捕获的SQLSTATE代码的简写

案例

我们继续来完成在上一小节提出的这个需求,并解决其中的问题。
根据传入的参数uage,来查询用户表tb_user中,所有的用户年龄小于等于user_age的用户姓名(name)和专业(profession),并将用户的姓名和专业插入到所创建的一张新表(id,name,profession)中。

A. 通过SQLSTATE指定具体的状态码

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
33
34
35
36
37
38
39
40
41
42
43
44
-- 逻辑:
-- A. 声明游标, 存储查询结果集
-- B. 准备: 创建表结构
-- C. 开启游标
-- D. 获取游标中的记录
-- E. 插入数据到新表中
-- F. 关闭游标
drop procedure if exists p1;
create procedure p1(in user_age int)
begin
declare user_name varchar(30);
declare user_profession varchar(30);
declare user_cursor cursor for select name, profession from tb_user where age <= user_age;
-- 声明条件处理程序 : 当SQL语句执行抛出的状态码为02000时,将关闭游标user_cursor,并退出
declare exit handler for sqlstate '02000' close user_cursor;
drop table if exists tb_user_pro;
create table tb_user_pro(
id int primary key auto_increment,
name varchar(30),
profession varchar(30)
);

open user_cursor;
while true do
fetch user_cursor into user_name, user_profession;
insert into tb_user_pro(name, profession) values(user_name, user_profession);
end while;
close user_cursor;
end




mysql> call p1(20);
Query OK, 0 rows affected (0.03 sec)

mysql> select * from tb_user_pro;
+----+------+------------+
| id | name | profession |
+----+------+------------+
| 1 | 廉颇 | 土木工程 |
| 2 | 后羿 | 城市园林 |
+----+------+------------+
2 rows in set (0.00 sec)

通过SQLSTATE的代码简写方式 NOT FOUND
02 开头的状态码,代码简写为 NOT FOUND

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
33
34
35
36
37
drop procedure if exists p1;
create procedure p1(in user_age int)
begin
declare user_name varchar(30);
declare user_profession varchar(30);
declare user_cursor cursor for select name, profession from tb_user where age <= user_age;
-- 声明条件处理程序 : 当SQL语句执行抛出的状态码为02开头时,将关闭游标user_cursor,并退出
declare exit handler for not found close u_cursor;
drop table if exists tb_user_pro;
create table tb_user_pro(
id int primary key auto_increment,
name varchar(30),
profession varchar(30)
);

open user_cursor;
while true do
fetch user_cursor into user_name, user_profession;
insert into tb_user_pro(name, profession) values(user_name, user_profession);
end while;
close user_cursor;
end




mysql> call p1(20);
Query OK, 0 rows affected (0.03 sec)

mysql> select * from tb_user_pro;
+----+------+------------+
| id | name | profession |
+----+------+------------+
| 1 | 廉颇 | 土木工程 |
| 2 | 后羿 | 城市园林 |
+----+------+------------+
2 rows in set (0.00 sec)

更多详细的错误状态码,可以参考官方文档:
https://dev.mysql.com/doc/refman/8.0/en/declare-handler.html
https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html