目录
1存储过程介绍
存储过程是事先经过编译并存储在数据库中的一段 SQL 语句的集合,调用存储过程可以简化应用开发人员的很多工作,减少数据在数据库和应用服务器之间的传输,对于提高数据处理的效率是有好处的。
存储过程思想上很简单,就是数据库 SQL 语言层面的代码封装与重用。
特点:
(1)封装,复用:可以把某一业务SQL封装在存储过程中,需要用到的时候直接调用即可。
(2)可以接收参数,也可以返回数据:再存储过程中,可以传递参数,也可以接收返回值。
(3)减少网络交互,效率提升:如果涉及到多条SQL,每执行一次都是一次网络传输。 而如果封装在存储过程中,我们只需要网络交互一次可能就可以了。
2存储过程基本语法
2.1创建存储过程
案例:封装统计student总记录数的操作
create procedure p1()
begin
select count(*) from student;
end;
2.2调用存储过程
call p1(); #括号不能少
调用p1,就会去执行这个存储过程中封装的逻辑。
2.3查看存储过程
(1)查看指定数据库的存储过程及状态信息
select * from information_schema.ROUTINES where ROUTINE_SCHEMA='itheima';
查看information_schema数据库中ROUTINES表中存放的,itheima数据库中的存储过程。
发现现在只有一个叫p1的存储过程。
(2)查询某个存储过程的定义
show create procedure p1;
2.4删除存储过程
drop procedure if exists p1;
删除之后再调用就不存在了。
此外,可以在命名窗口(或finalshell)输入delimiter + 自定义结束符,否则默认的是;
3变量
在MySQL中变量分为三种类型: 系统变量、用户定义变量、局部变量。
3.1系统变量
系统变量 是MySQL服务器提供,不是用户定义的,属于服务器层面。分为全局变量(GLOBAL)、会话 变量(SESSION)。
(1)全局变量(GLOBAL): 全局变量针对于所有的会话。
(2)会话变量(SESSION): 会话变量针对于单个会话,在另外一个会话窗口就不生效了。
3.1.1查看变量
如果没有指定SESSION/GLOBAL,默认是SESSION,会话变量。
mysql服务重新启动之后,所设置的全局参数会失效,要想不失效,可以在 /etc/my.cnf 中配置。
前面的案例:
MySQL的慢查询日志默认没有开启,我们可以查看一下系统变量 slow_query_log。
输入:show variables like 'slow_query_log';发现默认没有开启。
(1)查看所有系统变量
show session variables ;
(2)可以通过LIKE模糊匹配方 式查找变量
show session variables like 'auto%';
(3)查看指定变量的值
用select而不是show了。
Select @@autocommit;
3.1.2设置系统变量
这里设置没有指定,默认是SESSION,当前会话,不会影响其他会话。
所以换一个会话窗口这个系统变量并没有被改变:
3.2 用户自定义变量
用户定义变量 是用户根据需要自己定义的变量,用户变量不用提前声明,在用的时候直接用 "@变量 名" 使用就可以。其作用域为当前连接。
(1)赋值方式一:用set
set @myname='it';
set @myage =10;
查看:
select @myname,@myage;
(2)赋值方式二:
用select(还可以用计算字段count(*),且@mycount不用提前声明直接用)
select count(*) into @mycount from tb_user;
select @mycount;
3.3 局部变量
局部变量是根据需要定义的在局部生效的变量,访问之前,需要DECLARE声明。可用作存储过程内的局部变量和输入参数,局部变量的范围是在其内声明的BEGIN ... END块。
案例:
create procedure p2() #创建存储过程
begin
declare stu_count int default 0; #声明局部变量
select count(*) into stu_count from student;
select stu_count;
end; # stu_count的范围必须在其中
call p2;
4 if判断
在if条件判断的结构中,ELSE IF 结构可以有多个,也可以没有。 ELSE结构可以有,也可以没有。if 用于做条件判断,具体的语法结构为:
案例:
根据定义的分数score变量,判定当前分数对应的分数(58)等级。
score >= 85分,等级为优秀。
score >= 60分 且 score < 85分,等级为及格。
score < 60分,等级为不及格。
SQL代码:
create procedure p4()
begin
declare score int default 58;
declare result varchar(10);
if score>85 then
set result='优秀';
elseif score>=60 then
set result='及格';
else
set result='不及格';
end if;
select result;
end;
call p4();
5 存储过程的参数
参数的类型,主要分为以下三种:IN、OUT、INOUT。 具体的含义如下:
用法:
5.1 案例一 IN和OUT
根据传入参数score,判定当前分数对应的分数等级,并返回。
score >= 85分,等级为优秀。
score >= 60分 且 score < 85分,等级为及格。
score < 60分,等级为不及格。
SQL代码:
create procedure p5(in score int,out result varchar(10))
begin
if score>85 then
set result='优秀';
elseif score>=60 then
set result='及格';
else
set result='不及格';
end if;
end;
call p5(68,@result);
select @result;
不需要再declare了,直接在存储过程中声明in和out
5.2 案例二 INOUT
将传入的200分制的分数,进行换算,换算成百分制,然后返回。
SQL代码:
create procedure p6(INOUT score double)
begin
set score := score*0.5;
end;
set @score1=78;
call p6(@score1);
select @score1;
6 case
case结构及作用,和我们在基础篇中所讲解的流程控制函数很类似。有两种语法格式:
语法一:
语法二:
案例:判断月份所在的季度。根据传入的月份,判定月份所属的季节(要求采用case结构)。
1-3月份,为第一季度
4-6月份,为第二季度
7-9月份,为第三季度
10-12月份,为第四季度
SQL代码:
create procedure p8(in month int)
begin
declare result varchar(10);
case
when month>=1 and month<=3 then
set result='第一季度';
when month>=4 and month<=6 then
set result='第二季度';
when month>=7 and month<=9 then
set result='第三季度';
when month>=10 and month<=12 then
set result='第四季度';
else
set result='非法参数';
end case;
select concat('输入月份: ',month,'输出季度: ',result);
end;
call p8(3);
7 循环结构
7.1while
while 循环是有条件的循环控制语句。满足条件后,再执行循环体中的SQL语句。具体语法为:
案例:计算从1累加到n的值,n为传入的参数值。
我的SQL代码:6累加结果为21
create procedure p12(in n int)
begin
declare result int default 0;
declare i int default 1;
while i<=n do
set result = result + i;
set i=i+1;
end while;
select result;
end;
call p12(6);
或SQL代码:
create procedure p11(in n int)
begin
declare result int default 0;
while n>0 do
set result = result + n;
set n = n-1; # 就不用定义额外的变量
end while;
select result;
end;
call p11(6);
7.2 repeat
repeat是有条件的循环控制语句, 当满足until声明的条件的时候,则退出循环 。
具体语法为:注意until后面没分号;!!!
还是累加案例:
create procedure p13(in n int)
begin
declare result int default 0;
repeat
set result := result + n;
set n := n-1;
until n<=0
end repeat;
select result;
end;
call p11(7);
7.3 loop
LOOP 实现简单的循环,如果不在SQL逻辑中增加退出循环的条件,可以用其来实现简单的死循环。LOOP可以配合一下两个语句使用:
(1)LEAVE :配合循环使用,退出循环。
(2)ITERATE:必须用在循环中,作用是跳过当前循环剩下的语句,直接进入下一次循环。
累加案例:(个人感觉花里胡哨没有while和case明了)
8游标 cursor
游标(CURSOR)是用来存储查询结果集的数据类型(而不是只能返回单行单列) , 在存储过程和函数中可以使用游标对结果集进行循环的处理。游标的使用包括游标的声明、OPEN、FETCH 和 CLOSE,其语法分别如下。
案例:
根据传入的参数uage,来查询用户表tb_user中,所有的用户年龄小于等于uage的用户姓名 (name)和专业(profession),并将用户的姓名和专业插入到所创建的一张新表 (id,name,profession)中。
逻辑:
A. 声明游标, 存储查询结果集
B. 准备: 创建表结构
C. 开启游标
D. 获取游标中的记录
E. 插入数据到新表中
F. 关闭游标
SQL代码:
create procedure p14(in uage int)
begin
#A. 声明游标, 存储查询结果集
declare uname varchar(100);
declare ugender varchar(100);
declare u_cursor cursor for select name,gender from user where age<=uage;
#B. 准备: 创建表结构
drop table if exists tb_user_pro;
create table if not exists tb_uer_pro(
id int primary key auto_increment,
name varchar(100),
gender varchar(100)
);
#C. 开启游标
open u_cursor;
#D. 获取游标中的记录
while true do
#E. 插入数据到新表中
fetch u_cursor into uname,ugender;
insert into tb_uer_pro values (null,uname,ugender);
end while;
#F. 关闭游标
close u_cursor;
end;
call p14(20);
结果报错,但是新表已经创建好了,而且里面也有数据了
之所以报错是因为上面的while循环中,并没有 退出条件。当游标的数据集获取完毕之后,再次获取数据,就会报错,从而终止了程序的执行。
要想解决这个问题,就需要通过MySQL中提供的 条件处理程序 Handler 来解决。
9条件处理程序handler
条件处理程序(Handler)可以用来定义在流程控制结构执行过程中遇到问题时相应的处理步骤。具体语法为:
还是8中的案例SQL代码为:
create procedure p14(in uage int)
begin
#A. 声明游标, 存储查询结果集
declare uname varchar(100);
declare ugender varchar(100);
declare u_cursor cursor for select name,gender from user where age<=uage;
#声明条件处理程序 : 当SQL语句执行抛出的状态码为02000时,将关闭游标u_cursor,并退出
declare exit handler for sqlstate '02000' close u_cursor;
#B. 准备: 创建表结构
drop table if exists tb_user_pro;
create table if not exists tb_uer_pro(
id int primary key auto_increment,
name varchar(100),
gender varchar(100)
);
#C. 开启游标
open u_cursor;
#D. 获取游标中的记录
while true do
#E. 插入数据到新表中
fetch u_cursor into uname,ugender;
insert into tb_uer_pro values (null,uname,ugender);
end while;
#F. 关闭游标
close u_cursor;
end;
call p14(20);
成功运行没有报错了:
具体的错误状态码,可以参考官方文档:
https : // dev.mysql. com/doc/refman/8.0/en/declare-handler.html
https : / /dev.mysql .com/doc/mysql-errors/8 . 0/en/server-error-referen. html