存储过程简单来讲,就是为之后的使用而保存的一条或多条MySQL语句的集合。可将其视为批文件,虽然它们的做用不只限于批处理。使用存储过程须要MySQL5及之后的版本支持。node
经过把处理封闭在容易使用的单元中,简化复杂的操做;将一系列处理步骤放到同一存储过程当中,保证了数据的完整性和操做的安全性;简化对变动的管理;提升性能。mysql
使用存储过程比使用单独的SQL语句要快;sql
存在一些只能用在单个请求中的MySQL元素和特性,存储过程可使用它们来编写功能更强更灵活的代码;安全
CREATE PROCEDURE sp_name ([proc_parameter[,...]])ide
[characteristic ...] routine_body函数
proc_parameter:性能
[ IN | OUT | INOUT ] param_name typespa
create procedure sp_test()3d
beginblog
select name,classes_name from student222;
end
CALL sp_name;
call sp_test;
DROP PROCEDURE [ IF EXISTS ] sp_name;
drop procedure if exists sp_test;
SHOW CREATE PROCEDURE sp_name;
show create procedure sp_test;
show procedure status like 'sp_test';
(1)IN参数:只用来向过程传递信息,为默认值,在MySQL存储过程内部可能会修改此参数,但in类型参数的修改对调用者(caller)来讲是不可见的。
create procedure pr_param_in(in id int)
begin
if (id is not null) then
set id=id+1;
end if;
select id as id_inner;
end;
set @id=10;
call pr_param_in(@id);
select @id as id_out;
能够看到用户变量@id传入值为10,执行存储过程后,在过程内部值为:11(id_inner),但外部变量值依旧为:10(id_out)
===================================================================================
(2)OUT参数:只用来从过程传回信息,传值给调用者,在存储过程内部,该参数初始值为 null,不管调用者是否给存储过程参数设置值。
create procedure pr_param_out(out id int)
begin
select id as id_inner_1;
if (id is not null) then
set id=id+1;
select id as id_inner_2;
else
select 1 into id; -- 使用select...into...传回值给out参数
end if;
select id as id_inner_3;
end;
set @id=10;
call pr_param_out(@id);
select @id as id_out;
能够看出,虽然咱们设置了用户定义变量@id为10,传递@id给存储过程后,在存储过程内部,id的初始值老是 null(id_inner_1)。最后id值(id_out=1)传回给调用者。
===================================================================================
(3)INOUT参数能够向过程传递信息,也能够从存储过程内部传值给调用者。
create procedure pr_param_inout(inout id int)
begin
select id as id_inner_1;
if (id is not null) then
set id=id+1;
select id as id_inner_2;
else
select 1 into id;
end if;
select id as id_inner_3;
end;
set @id=10;
call pr_param_inout(@id);
select @id as id_out;
从结果能够看出:咱们把 @id(10)传给存储过程后,存储过程最后又把计算结果值11(id_inner_3)
传回给调用者。
===================================================================================
经过以上例子:
1) 若是仅仅想把数据传给MySQL存储过程,那就用in类型参数;
2) 若是仅仅从MySQL存储过程返回值,那就用out类型参数;
3) 若是须要把数据传给MySQL存储过程通过计算再传回给咱们,那就用inout类型参数。
===================================================================================
【参数名和列名不要重名,不然会出错;BEGIN..End间声明的变量名不能与关键字重名;mysql中不能采用select left1=Lft from table where...的方式获取值!只能用set为变量赋值】----这个规则也适用于函数
create procedure CountLayer(IN nodeid int,OUT x1 int)
begin
declare left1 int;
declare right1 int;
set left1=(select Lft from treelevel where Node_id = nodeid);
set right1=(select Rgt from treelevel where Node_id = nodeid);
select count(*) into x1 from treelevel where Lft<=left1 and Rgt>=right1;
end
call CountLayer(1,@xx);
select @xx;
===================================================================================
create procedure sp_type_cnt(IN in_type varchar(20),OUT out_cnt int)
BEGIN
select count(*) from classes222 where name =in_type into out_cnt;
END
call sp_type_cnt('AA班',@cnt);
select @cnt;