一、存储过程介绍
- 存储过程是一组为了完成特殊功能的SQL语句集合
- 【存储过程在使用过程中是将常用或者复杂的工作预先使用SQL语句写好并用一个指定的名称存储起来,这个过程经编译和优化后存储在数据库服务器中。当需要使用该存储过程时,只需要调用它即可。存储过程在执行上比传统SQL速度更快、执行效率更高。
存储过程的优点:
- 执行一次后,会将生成的二进制代码驻留缓冲区,提高执行效率
- SQL语句加上控制语句的集合,灵活性高
- 在服务器端存储,客户端调用时,降低网络负载
- 可多次重复被调用,可随时修改,不影响客户端调用
- 可完成所有的数据库操作,也可控制数据库的信息访问权限
二、存储过程操作
1、创建存储过程
DELIMITER $$ #将语句的结束符号从分号;临时改为两个$$(可以是自定义)
CREATE PROCEDURE Proc() #创建存储过程,过程名为Proc,不带参数
-> BEGIN #过程体以关键字 BEGIN 开始
-> select * from Store_Info; #过程体语句
-> END $$ #过程体以关键字 END 结束
DELIMITER ; #将语句的结束符号恢复为分号
mysql> delimiter $$
mysql> create procedure xc()
-> begin
-> select * from test;
-> end $$
Query OK, 0 rows affected (0.01 sec)
mysql> delimiter ;
mysql> call xc;
注意:创建存储过程必须在一个库中
2、调用存储过程
CALL xc;
3、查看存储过程
SHOW CREATE PROCEDURE [数据库.]存储过程名; #查看某个存储过程的具体信息
show create procedure client.xc\G
show create procedure xc\G
4、存储过程的参数
- IN 输入参数:表示调用者向过程传入值(传入值可以是字面量或变量)
- OUT 输出参数:表示过程向调用者传出值(可以返回多个值)(传出值只能是变量)
- INOUT 输入输出参数:既表示调用者向过程传入值,又表示过程向调用者传出值(值只能是变量)
select * from store;
delimiter $$
create procedure xc2(in inname char(10))
begin
select * from store where store_name=inname;
end $$
call xc2('houston');
delimiter $$
create procedure xc3(in myname char(10),out outname int)
begin
select sales into outname from store where store_name=myname;
end $$
delimiter ;
call xc3('houston',@out);
select @out;
delimiter $$
create procedure xc4(inout insales int)
begin
select count(sales) into insales from store where sales < insales;
end$$
delimiter ;
set @inout=800
call xc4(@inout);
select @inout
5、删除存储过程
- 存储过程内容的修改方法是通过删除原有存储过程,之后再以相同的名称创建新的存储过程。如果要修改存储过程的名称,可以先删除原存储过程,再以不同的命名创建新的存储过程。
DROP PROCEDURE IF EXISTS Proc; #仅当存在时删除,不添加 IF EXISTS 时,如果指定的过程不存在,则产生一个错误
drop procedure xc3;
show procedure status xc3;
show procedure status like '%xc3%';
6、存储过程的控制语句
create table t (id int(10));
insert into t values(10);
- 条件语句
if-then-else ···· end if
DELIMITER $$
CREATE PROCEDURE proc2(IN pro int)
-> begin
-> declare var int;
-> set var=pro*2;
-> if var>=10 then
-> update t set id=id-1;
-> else
-> update t set id=id+1;
-> end if;
-> end $$
DELIMITER ;
CALL Proc2(6);
- 循环语句
while ···· end while
DELIMITER $$
CREATE PROCEDURE proc3()
-> begin
-> declare var int(10);
-> set var=0;
-> while var<6 do
-> insert into t values(var);
-> set var=var+1;
-> end while;
-> end $$
DELIMITER ;
CALL Proc3;