存储过程:一组预先编译好的SQL语句的集合,理解成批处理语句,类似于Java中的方法
- 提高代码的重用性
- 简化操作
- 减少了编译次数并且减少了和数据库服务器的连接次数,提高了效率
创建语法:
create procedure 存储过程名(参数列表)
begin
存储过程体(一组合法的SQL语句)
end
# 参数列表包含三部分
参数列表 参数名 参数类型
IN stuname varchar(20)
参数模式:
- IN:该参数可以作为输入,也就是该参数需要调用方传入值
- OUT:该参数可以作为输出,也就是该参数可以作为返回值
- INOUT:该参数既可以作为输入又可以作为输出,也就是该参数既需要传入值,又可以返回值
- 如果存储过程体仅仅只有一句话,begin end可以省略
- 存储过程体中的每条SQL语句的结尾要求必须加分号
- 存储过程的结尾可以使用delimiter重新设置,语法为
delimiter $
- 调用语法为
call 存储过程名(实参列表)
空参存储过程:
delimiter $
create procedure myp1()
begin
insert into boys values(3, 'gom', 123456);
end $
call myp1()
带in存储过程:
create procedure myp2(IN beautyName varchar(20))
begin
select bo.*
from boys bo
right join beauty b on bo.id = b.boyfriend_id
where b.name = beautyName
end
call myp2('柳岩') $
带out存储过程:
create procedure myp3(IN beautyName varchar(20), OUT boyName varchar(20))
begin
select bo.boyName INTO boyName
from boys bo
inner join beauty b on bo.id = b.boyfriend_id
where b.name = beautyName
end
call myp3('小昭', @boyName) $
create procedure myp4(IN beautyName varchar(20), OUT boyName varchar(20), OUT userCP INT)
begin
select bo.boyName, bo.userCP INTO boyName, userCP
from boys bo
inner join beauty b on bo.id = b.boyfriend_id
where b.name = beautyName
end
call myp4('小昭', @boyName, @userCP) $
带INOUT的存储过程:
create procedure myp5(INOUT a INT, INOUT b INT)
begin
set a=a*2;
set b=b*2;
end
存储过程的删除:
drop procedure 存储过程名
查看存储过程:
show create procedure myp2;
存储过程和函数的区别:
- 存储过程:可以有0个返回,也可以有多个返回,适合做批量插入、批量更新
- 函数:有且仅有1个返回,适合做处理数据后返回一个结果
创建函数:
create function 函数名(参数列表) returns 返回类型
begin
函数体
end
# 函数体中一定有return语句,否则会报错,要记得使用delimiter语句设置结束标记
# 返回公司的员工个数
create function myf1() returns int
begin
declare c int default 0;
select count(*) into c
from employees;
return c;
end $
myf1() $
函数的查看和删除:
drop function myf3;
show create function myf3;