文章目录
1、存储过程和函数概念
存储过程和函数是 事先经过编译并存储在数据库中的一段 SQL 语句的集合,调用存储过程和函数可以简化应用开发人员的很多工作,减少数据在数据库和应用服务器之间的传输,对于提高数据处理的效率是有好处的
存储过程和函数的区别在于函数必须有返回值,而存储过程没有
函数:是一个有返回值的过程
过程:是一个没有返回值的函数
2、存储过程的使用
(1)创建存储过程
创建存储过程的语法
CREATE PROCEDURE procedure_name ([proc_parameter[,...]])
begin
-- SQL语句
end ;
首先学习一个语句,delimiter $
作用是自定义分隔符,也就是说,使用$来表示命令是否结束
delimiter $
create PROCEDURE pro_test()
begin
select 'Hello MySQL';
end$
(2)调用存储过程
call 存储过程的名称;
(3)查看存储过程
select name from mysql.proc where db = 'demo_01';
查看存储过程的详细信息
show create procedure pro_test\G$
(4)删除存储过程
语法
DROP PROCEDURE [IF EXISTS] sp_name;
drop procedure if exists pro_test;
3、存储过程的语法
(1)声明变量
声明变量并且设置默认值
DECLARE var_name[,...] type [DEFAULT value]
declare num int default 10;
先声明变量,后赋值
SET var_name = expr [, var_name = expr] ...
也可以通过查询赋值,使用into
指定
(2)if条件判断
语法
if search_condition then statement_list
[elseif search_condition then statement_list] ...
[else statement_list]
end if;
create procedure pro_test4()
begin
declare height int default 175;
declare description varchar(50) default '';
if height >= 180 then
set description = '身材高挑';
elseif height >= 170 and height < 180 then
set description = '标准身材';
else
set description = '一般身材';
end if;
select concat('身高 ', height, '身材类型:', description);
end$
(3)传递参数
语法
create procedure procedure_name([in/out/inout] 参数名 参数类型)
...
IN : 该参数可以作为输入,也就是需要调用方传入值 , 默认
OUT: 该参数作为输出,也就是该参数可以作为返回值
INOUT: 既可以作为输入参数,也可以作为输出参数
- IN类型参数案例:根据定义的身高变量,判定当前身高的所属的身材类型
create procedure pro_test5(in height int)
begin
declare description varchar(50) default '';
if height >= 180 then
set description = '身材高挑';
elseif height >= 170 and height < 180 then
set description = '标准身材';
else
set description = '一般身材';
end if;
select concat('身高 ', height, '身材类型:', description);
end$
- OUT类型参数案例:根据传入的身高变量,获取当前身高的所属的身材类型
create procedure pro_test6(in height int, out description varchar(50))
begin
if height >= 180 then
set description = '身材高挑';
elseif height >= 170 and height < 180 then
set description = '标准身材';
else
set description = '一般身材';
end if;
select concat('身高 ', height, '身材类型:', description);
end$
call pro_test6(188, @description)$
select @description$
@description : 这种变量要在变量名称前面加上“@”符号,叫做用户会话变量,代表整个会话过程他都是有作用的,这个类似于全局变量一样。
@@global.sort_buffer_size : 这种在变量前加上 “@@” 符号, 叫做 系统变量
(4)case结构
语法
方式一 :
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE;
方式二 :
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE;
案例:给定一个月份, 然后计算出所在的季度
create procedure pro_test7(mon int)
begin
declare result varchar(10);
case
when mon >= 1 and mon <= 3 then
set result = '第一季度';
when mon >= 4 and mon <= 6 then
set result = '第一季度';
when mon >= 7 and mon <= 9 then
set result = '第一季度';
when mon >= 10 and mon <= 12 then
set result = '第一季度';
else
set result = '请输入1~ 12之间的数字';
end case;
select concat('判断结果为:', result);
end$
(5)while循环
语法
while search_condition do
statement_list
end while;
示例:计算从1加到n的值
create procedure pro_test8(n int)
begin
declare total int default 0;
declare num int default 1;
while num <= n do
set total = total + num;
set num = num + 1;
end while;
select concat('结果为:', total);
end$
(6)repeat结构
有条件的循环控制语句, 当满足条件的时候退出循环 。while 是满足条件才执行,repeat 是满足条件就退出循环,具体语法如下
REPEAT
statement_list
UNTIL search_condition
END REPEAT;
示例:计算从1加到n的值
create procedure pro_test9(n int)
begin
declare total int default 0;
repeat
set total = total + n;
set n = n - 1;
until n = 0
end repeat;
select concat('结果为:', total);
end$
(7)loop语句
LOOP 实现简单的循环,退出循环的条件需要使用其他的语句定义,通常可以使用 LEAVE 语句实现,具体语法如下
[begin_label:] LOOP
statement_list
END LOOP [end_label]
如果不在 statement_list 中增加退出循环的语句,那么 LOOP 语句可以用来实现简单的死循环
(8)leave语句
用来从标注的流程构造中退出,通常和 BEGIN … END 或者循环一起使用。下面是一个使用 LOOP 和 LEAVE 的简单例子 , 退出循环
create procedure pro_test10(n int)
begin
declare total int default 0;
c:loop
set total = total + n;
set n = n - 1;
if n <= 0 then
leave c;
end if;
end loop c;
select concat('结果为:', total);
end$
(9)游标/光标
游标是用来存储查询结果集的数据类型 , 在存储过程和函数中可以使用光标对结果集进行循环的处理。光标的使用包括光标的声明、OPEN、FETCH 和 CLOSE,其语法分别如下
- 声明光标:
DECLARE cursor_name CURSOR FOR select_statement ;
- OPEN 光标:
OPEN cursor_name ;
- FETCH 光标:
FETCH cursor_name INTO var_name [, var_name] ...
- CLOSE 光标:
CLOSE cursor_name ;
测试案例,初始化测试数据
create table emp(
id int(11) not null auto_increment ,
name varchar(50) not null comment '姓名',
age int(11) comment '年龄',
salary int(11) comment '薪水',
primary key(`id`)
)engine=innodb default charset=utf8 ;
insert into emp(id,name,age,salary) values(null,'金毛狮王',55,3800),(null,'白眉鹰王',60,4000),(null,'青翼蝠王',38,2800),(null,'紫衫龙王',42,1800);
示例:查询emp表中数据, 并逐行获取进行展示
create procedure pro_test11()
begin
declare e_id int(11);
declare e_name varchar(50);
declare e_age int(11);
declare e_salary int(11);
declare emp_result cursor for select * from emp;
open emp_result;
fetch emp_result into e_id, e_name, e_age, e_salary;
select concat('id=', e_id , ', name=', e_name, ', age=', e_age, ', 薪资为: ', e_salary);
fetch emp_result into e_id, e_name, e_age, e_salary;
select concat('id=', e_id , ', name=', e_name, ', age=', e_age, ', 薪资为: ', e_salary);
fetch emp_result into e_id, e_name, e_age, e_salary;
select concat('id=', e_id , ', name=', e_name, ', age=', e_age, ', 薪资为: ', e_salary);
fetch emp_result into e_id, e_name, e_age, e_salary;
select concat('id=', e_id , ', name=', e_name, ', age=', e_age, ', 薪资为: ', e_salary);
close emp_result;
end$
通过循环结构 , 获取游标中的数据
create procedure pro_test12()
begin
declare e_id int(11);
declare e_name varchar(50);
declare e_age int(11);
declare e_salary int(11);
declare has_data int default 1;
declare emp_result cursor for select * from emp;
declare exit handler for not found set has_data = 0;
open emp_result;
repeat
fetch emp_result into e_id, e_name, e_age, e_salary;
select concat('id=', e_id , ', name=', e_name, ', age=', e_age, ', 薪资为: ', e_salary);
until has_data = 0
end repeat;
close emp_result;
end$
4、存储函数
(1)创建存储函数
CREATE FUNCTION function_name([param type ... ])
RETURNS type
BEGIN
...
END;
案例:定义一个存储过程, 请求满足条件的总记录数
create function fun1(countryId int)
returns int
begin
declare cnum int;
select count(*) into cnum from city where(country_id = countryId;
return cnum;
end$
(2)删除存储函数
drop function fun1()$