存储过程
简单来说,就是为以后的使用而保存的一条或多条MySQL语句的集合。可将其视为批件,
虽然它们的作用不仅限于批处理。
存储过程就是有业务逻辑和流程的集合, 可以在存储过程中创建表,更新数据, 删除等等。
为什么要使用存储过程
1.通过把处理封装,在容易使用的单元中,简化复杂的操作(正如前面例子所述)。
2.由于不要求反复建立一系列处理步骤,这保证了数据的完整性。如果所有开发人员和应用程序都使用同一(试验和测试)存储过程,则所使用的代码都是相同的。这一点的延伸就是防止错误。 需要执行的步骤越多,出错的可能性就越大。防止错误保证了数据的一致性。
3.简化对变动的管理。如果表名、列名或业务逻辑(或别的内容)有变化,只需要更改存储过程的
代码。使用它的人员甚至不需要知道这些变化。
-------------------
一个简单的存储过程
create produce produceName()
begin
select name from user;
end;
调用存储过程:
call produceName();
删除存储过程:
drop produce if exists produceName;
-----------------------
使用参数的存储过程:
create produce produceName(
out min decimal(8,2),
out avg decimal(8,2),
out max decimal(8,2)
)
begin
select MIN(price) into min from order;
select AVG(price) into avg from order;
select MAX(price) into max from order;
END;
MySQL支持IN(传递给存储过程)、OUT(从存储过程传出,如这里所用)和INOUT(对存储过程传入和传出)类型的参数。
存储过程的代码位于BEGIN和END语句内,如前所见,它们是一系列SELECT语句,用来检索值,然后保存到相应的变量(通过指定INTO关键字)调用此修改过的存储过程,必须指定3个变量名:call produceName(@min,@avg,@max);然后即可调用显示该变量的值:
select @min,@avg,@max;
--------------------------------
使用in参数, 输入一个用户id, 返回该用户所有订单的总价格
create procedure getTotalById (
in userId int,
out total decimal(8,2)
)
BEGIN
- select SUM(r.price) from order r
- where r.u_id = userId
into total;
END;
调用存储过程
call getTotalById(1,@total);
select
@
total;
---------------------------------------------
复杂一点的过程, 根据用户id获取该用户的所有订单价格, 并动态的选择是否加税。代码设计如下
create procedure getTotalByUser2(
in userId int,
in falg boolean, --是否加税标记
out total decimal(8,2)
)
begin
DECLARE tmptotal DECIMAL(8,2);
DECLARE taxrate int DEFAULT 6;--?默认的加税的利率
select SUM(r.price) from order r
where r.u_id = userId
into tmptotal;
if falg then
select tmptotal + (tmptotal/1000*taxrate) into mptotal;
end if;
select tmptotal into total;
END;
该过程传入三个参数, 用户id, 是否加税以及返回的总价格,在过程内部, 定义两个局部变量tmptotal和taxrate,把查询出来的结果赋给临时变量, 在判断是否加税。最后把局部变量的值赋给输出参数。
call getTotalByUser2(1, false,
@
total); -- 不加税
call getTotalByUser2(1, true, @total); --加税
select
@
total;