SQL必知必会-笔记(十)存储过程

存储过程就是为以后使用而保存的一条或多条SQL语句。

为什么使用存储过程?

  • 安全,简单,高性能
    • 通过把处理封装在容易使用的单元中,简化复杂的操作
    • 由于不要求反复建立一系列处理步骤,这保证了数据的完整性。如果所有开发人员和应用程序都使用同一(试验和测试)存储过程,则所使用的代码都是相同的。这一点的延伸就是防止错误。需要执行的步骤越多,出错的可能性就越大。防止错误保证了数据的一致性。
    • 简化对变动的管理
    • 提高性能。因为使用存储过程比使用单独的SQL语句要快

创建存储过程

create procedure productpricing(
  out pl decimal(8,2),
  out ph decimal(8,2),
  out pa decimal(8,2)
)
begin
  select min(prod_price) into pl from Products;
  select max(prod_price) into ph from Products;
  select avg(prod_price) into pa from Products;
end;

此存储过程接受3个参数: pl存储产品最低价格, ph存储产品最高价格, pa存储产品平均价格。每个参数必须具有指定的类型,这里使用十进制值。MySQL支持IN(传递给存储过程)、OUT(从存储过程传出,如这里所用)和INOUT(对存储过程传入和传出)类型的参数。

调用存储过程

call productpricing(@pricelow,@pricehigh,@priceavg);
select @pricehigh,@priceavg,@pricelow;

再看一个例子,ordertotal接受订单号并返回该订单的合计:

create procedure ordertotal(
  in onumber INT,
  out ototal decimal(8,2)
)
begin
  select sum(item_price*quantity) from OrderItems where order_num = onumber
  into ototal;
end;

call ordertotal(20005,@total);
select @total;

最后看一个比较完整的例子:

create procedure ordertotal(
  in onumber int,
  in taxable boolean,
  out ototal decimal(8,2)
)
begin
  declare total decimal(8,2);
  declare taxrate int default 6;

  -- get the order total
  select sum(item_price*quantity) from OrderItems where order_num = onumber
  into total;

  -- Is this taxable?
  if taxable then
    select total+(total/100*taxrate) into total;
  end if;

  select total into ototal;
end;

call ordertotal(20005,0,@total);
select @total;

首先,增加了注释(前面放置--)。在存储过程复杂性增加时,这样做特别重要。添加了另外一个参数taxable,它是一个布尔值(如果要增加税则为真,否则为假)。在存储过程体中,DECLARE语句定义了两个局部变量。 DECLARE要求指定变量名和数据类型,它也支持可选的默认值(这个例子中的taxrate的默认被设置为6%)。 SELECT语句已经改变,因此其结果存储到total(局部变量)而不是ototal。 IF语句检查taxable是否为真,如果为真,则用另一SELECT语句增加营业税到局部变量total。最后,用另一SELECT语句将total(它增加或许不增加营业税)保存到ototal。

原文地址:https://www.cnblogs.com/xLI4n/p/10348568.html