【进阶篇第五弹】《详解存储过程》从0掌握MySQL中的存储过程以及存储函数
文章目录
- 存储过程
- 一、基本语法
- (1)创建存储过程
- (2)调用存储过程
- (3)查看存储过程
- (4)删除存储过程
- (5)设置结束符
- (6)参数
- 二、变量
- (1)系统变量
- (2)用户自定义变量
- (3)局部变量
- 三、基本语句
- (1)if判断
- (2)case
- (3)while循环
- (4)repeat
- (5)loop循环
- 四、游标
- 五、条件处理程序
- 六、存储函数
存储过程
概念:
存储过程时事先编译并存储在数据库中的一段SQL语句的集合。
调用存储过程可以简化应用开发人员的很多工作,减少数据在数据库和应用服务器之间的传输,对于提高数据处理的效率是有好处的。
存储过程思想上很简单,就是数据库SQL语言层面的代码封装与重用。
特点:
- 封装,复用。
- 可以接收参数,也可以返回数据
- 减少网络交互,效率提升
一、基本语法
(1)创建存储过程
create procedure 存储过程名称([参数列表])
begin-- sql语句
end;
(2)调用存储过程
call 存储过程名称([参数列表])
(3)查看存储过程
-- 查询指定数据库的存储过程及状态信息
select * from information_schema.routines where routine_schema = 'xxx';-- 查询某个存储过程的定义
show create procedure 存储过程名称;
-
information_schema.routines
:系统视图,存储了数据库中所有存储过程和函数的元数据。 -
routine_schema = 'xxx'
:过滤条件,xxx
需替换为目标数据库名称,用于指定查询哪个数据库的存储过程。
(4)删除存储过程
drop procedure [if exists] 存储过程名称;l
(5)设置结束符
sql默认的结束符是分号;
但是存储过程中的SQL语句每一句结束都是分号;
导致存储过程无法正确执行。
这时候就需要修改结束的语句
delimiter $$
**但是自此以后,所有的sql语句都会需要$$**结束
CREATE PROCEDURE get_student(IN student_id INT)
BEGIN-- 内部SQL语句仍用;结束SELECT * FROM students WHERE id = student_id;SELECT COUNT(*) FROM scores WHERE student_id = student_id;
END $$ -- 这里用$$表示存储过程定义结束(与修改后的结束符一致)
#改回分号结束
delimiter ;
(6)参数
类型 | 含义 | 备注 |
---|---|---|
in | 该类参数作为输入,也就是需要调用时传入值 | 默认 |
out | 该类参数作为输出,也就是该参数可以作为返回值 | |
inout | 既可以作为输入参数,可以作为输出参数 |
- in/out:
传值和返回值;
-- 案例
-- 1.根据传入参数score,判定当前分数对应的分数等级,并返回。
-- score >= 85分,等级为优秀。
-- score >= 60分 且 score < 85分,等级为优秀。
-- score < 60分,等级为优秀。
create procedure p1(in score int,out result varchar(10))
beginif score >= 85 thenset result := '优秀';elseif score >= 60 thenset result := '及格';elseset result := '不及格';end if;
end;call p4(60,@result);
之后 select @result 就是’及格’了
- inout:
即将传入的值进行加工,改变传入值
-- 案例
-- 2.将传入的200分制的分数,进行换算,换算成百分制,然后返回分数 ---> inout
create procedure p2(inout score double)
beginset score := score * 0.5;
end;set @score = 200;
call p5(@score);
select @score; -- 输出为100
二、变量
(1)系统变量
系统变量是MySQL服务器提供,不是用户定义的,属于服务器层面。分为全局变量(global)、会话变量(seesion).
1.查看系统变量
不指定,默认选择session
show [session|global] variables; -- 查看所有系统变量
show [session|global] variables like '......'; -- 可以通过like模糊匹配方式查找变量,如'auto%'
select @@[session|global].系统变量名; -- 查看指定变量的值
2.设置系统变量
设置系统变量后,重启服务器会重新变为默认值;
如果 不想消失需要在/etc/my.cnf中配置
set [session|global] 系统变量名 = 值;
set @@[session|global].系统变量名;
(2)用户自定义变量
用户自定义变量是用户根据需要自己定义的变量,用户变量不用提前声明,在用的时候直接用’@变量名‘使用就可以。其作用域为当前连接。
- 赋值
set @变量名 = 值;
set @变量名 := 值;select @变量名 := 值;
select 字段名 into @变量名 from 表名;
- 使用
select @变量名;
注意:
用户定义的变量无需对齐进行声明或初始化,只不过获取到的值为NULL。
(3)局部变量
局部变量是根据需要定义在局部生效的变量,访问之前,需要用declare声明。可用作存储过程内的局本变量和输入参数,局部变量的范围是在其内声明的begin…end块。
- 声明
declare 变量名 变量类型[default...];
变量类型就是数据库字段类型:int、bigint、char、varchar、date、time等
- 赋值
set 变量名 = 值;
set 变量名 := 值;
select 字段名 into 变量名 from 表名...;
-- 例子
create procedure p1()
begindeclare stu_count int default 0;
end;
三、基本语句
(1)if判断
1.语法
if 条件1 then.....
elseif 条件2 then -- 可选.....
else -- 可选.....
end if;
2.练习
-- 根据定义的分数score变量,判断当前分数对应的分数等级。
-- 1.score >= 85分,等级为优秀。
-- 2.score >= 60分 且 score < 85分,等级为优秀。
-- 3.score < 60分,等级为优秀create procedure p1()
begindeclare score int default 58;declare result varchar(10);if score >= 85 thenset result := '优秀';elseif score >= 60 thenset result := '及格';elseset result := '不及格';end if;select resultl;
end;
(2)case
1.语法
- 语法一
case case_valuewhen when_value then 语句1;[when when_value then 语句2;][else 语句3];
end case;
when条件都不符合,就会进入else。
- 语法二
casewhen 条件判断 then 语句1;[when 条件判断 then 语句2;][else 语句3];
end case;
2.练习
-- 根据传入的月份,判定月份所属的季节(要求采用case结构)。
-- 1.1-3月份,为第一季度
-- 2.4-6月份,为第二季度
-- 3.7-9月份,为第三季度
-- 4.10-12月份,为第四季度create procedure p1(in month int)
begindeclare result varchar(10);casewhen month >= 1 and month <= 3 thenset result := '第一季度';when month >= 4 and month <= 6 thenset result := '第二季度';when month >= 7 and month <= 9 thenset result := '第三季度';when month >= 10 and month <= 12 thenset result := '第四季度';elseset result := '非法参数';end case;select concat('您输入的月份为:',month,'所属季度为:',result);end
(3)while循环
1.语法
while循环是有条件的循环控制语句。满足条件后,再执行循环体中的SQL语句。
-- 先判断条件,如果条件为true,则执行逻辑,否则,不执行逻辑
while 条件 doSQL逻辑....
end while;
2.练习
-- 计算1累加到n的值,n为传入的参数值。
create procedure p1(in n int)
begindeclare total int default 0;while n>0 doset total := total + n;set n := n - 1;end whileselect total;
end;
(4)repeat
1.语法
repeat是有条件的循环控制语句,当满足条件的时候退出循环。
-- 先执行一次逻辑,然后判断逻辑是否满足,如果满足,则退出。如果不满足,则继续下一次循环
repeatSQL逻辑....until 条件
end repeat;
2.练习
-- 计算1累加到n
create procedure p2(in n int)
begindeclare total int default 0;repeatset total := n + total;set n := n - 1;until n <= 0end repeat;select total;
end;
(5)loop循环
1.语法
loop实现简单的循环,如果不在SQL逻辑中增加退出循环的条件,可以用其实现简单的死循环。
loop可以配合以下两个语句使用:
leave:配合循环使用,退出循环。(跳出循环必用)
iterate:必须用在循环中,作用是跳过当前循环剩下的语句,直接进入下一次循环。
[begin_label:] loopSQL逻辑
end loop [end_label]
-- label有如下几种:
leave label; -- 退出指定标记的循环体
iterate label -- 直接进入下一次循环
2.练习
了解如何跳出循环、了解如何跳过当前循环进入下一次循环
(1)了解如何跳出循环leave
-- 1.计算从1累加到n的值,n为传入的参数值
create procedure p3(in n int)
begindeclare total int default 0;sum:loopif n<0 thenleave sum;end if;set total := total + n;set n := n-1;end loop sum;select total;
end;
(2)了解如何跳过当前循环进入下一次循环(iterate)
-- 2.计算从1到n之间的偶数累加的值,n为传入的参数值
create procedure p4(in n int)
begindeclare total int default 0;sum:loopif n<0 thenleave sum;end if;if n%2=1 thenset n := n-1;iterate sum;end if;set total := total + n;set n := n-1;end loop sum;select total;
end;
四、游标
(1)基本说明
游标(cursor)是用来存储查询结果集的数据类型,在存储过程和函数中可以使用游标对结果集进行循环的处理。游标的使用包括游标的声明、open、fetch和close。
游标需要声明在普通变量之后,否则会报错
-- 声明游标
declare 游标名称 cursor for 查询语句;
-- 打开游标
open 游标名称;
-- 获取游标记录
fetch 游标名称 into 变量[,变量...];
-- 关闭游标
close 游标名称;
(2)案例
根据传入的参数uage,来查询用户表tb_user中,所有的用户年龄小于等于uage的用户的姓名(name)和专业(profession),并将用户的姓名和专业插入到所创建的一张新表(id,name,profession)中。
-- 逻辑
-- 1.声明游标,存储查询结果集
-- 2.准备:创建表结构
-- 3.开启游标(open)
-- 4.获取游标中的记录(fetch)
-- 5.插入数据到新表中
-- 6.关闭游标(close)
create procedure p6(in max_age int)
begin-- 声明变量接收数据declare uname varchar(50) default null;declare uprofession varchar(50) default null;-- 1.声明游标,存储查询结果集declare u_cursor cursor for select name,profession from tb_user where age<max_age;-- 2.准备:创建表结构drop table if exists tb_user_pro;create table if not exists tb_user_pro(id int primary key auto_increment,name varchar(50),profession varchar(50));-- 3.开启游标open u_cursor;while true do-- 4.获取游标中的记录fetch u_cursor into uname,uprofession;-- 5.插入数据到新表insert into tb_user_pro(name,age) values (uname,uage);end while;-- 6.关闭游标close u_cursor;
end;
以上可以很容易看出,while的条件是true,一直为真,会导致fetch取到空数据从而报错,为了解决这个问题,我们有了条件处理程序;
-- 定义条件处理程序
declare exit handler for SQLSTATE '02000' close u_cursor;
-- exit放入while中即可
五、条件处理程序
条件处理程序(Handler)可以用来定义在流程控制结构执行过程中遇到问题时相应的处理步骤。
declare handler_action handler for conditon_value [,conditon_value]... satement;handler_acion:continue -- 继续执行当前程序exit -- 终止执行当前程序
conditon_value:sqlstate 状态码 -- 如:sqlstate 2000sqlwarning -- 所有01开头的sqlstate代码的简写not found -- 所有02开头的sqlstate代码的简写sqlexception -- 所有没有被sqlwarning和notfound捕获的sqlstate代码的简写
#状态码为02000
declare exit handler for SQLSTATE '02000' close u_cursor;#当状态为02开头语句时
declare exit handler for not found colse u_cursor;
六、存储函数
(1)基本说明
存储函数是有返回值的存储过程,存储函数的参数只能是in类型的。
能够使用存储函数的地方都可以用存储过程替代
create function 存储函数名称([参数列表])
returns 返回类型
[characteristic...] -- 特性名称
begin-- SQL语句return...;
end;-- characteristic说明:
deterministic -- 相同输入参数总是产生相同的结果
not sql -- 不包含sql语句
reads sql data -- 包含读取数据的语句,但不包含写入数据的语句
如果不加特性characteristic,会报错,如下图:
(2)案例
-- 计算从1累加到n的值,n为传入的参数值
create function fun1(n int)
returns int deterministic
begindeclare total int default 0;while n>0 doset total := total+n;set n := n-1;end while;return total;end;select fun1(100);