存储过程就是为以后使用而保存的一条或多条SQL语句。
此存储过程接受3个参数: pl存储产品最低价格, ph存储产品最高价格, pa存储产品平均价格。每个参数必须具有指定的类型,这里使用十进制值。MySQL支持IN(传递给存储过程)、OUT(从存储过程传出,如这里所用)和INOUT(对存储过程传入和传出)类型的参数。
再看一个例子,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