存储过程

基本概念

存储过程就是将一条或多条MySQL语句保存起来,方便以后的使用。类似于自定义的函数。

创建存储过程

create procedure 过程名()
begin
...
end
delimiter $$   //使用$$作为存储过程的分隔符
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关键字

call ordertotal(20005,@total);
select @total;//所有MySQL变量都必须以@开始

删除存储过程

drop procedure if exists ordertotal;//存在的时候删除

显示存储过程信息

show procedure status like 'ordertotal';
show create procedure ordertotal;

建立智能存储过程

  • 需求:获得订单合计,并且需要对某些顾客合计增加营业税
  • 思路:
    1.获得合计
    2.把营业税有条件的增加到合计
    3.返回合计
  • 具体实现:
    Name:ordertotal
    Parameters:
    onumber=order number
    taxable=0 if not taxable,1 if taxable
    ototal=order total variable
  • 代码
//创建存储过程
delimiter $$
create procedure ordertotal(
in onumber int,
in taxable boolean,
out ototal decimal(8,2)
)comment 'Obtain order total,optionally adding tax'
begin 
declare total decimal(8,2);
declare taxrate int default 6;  //声明存储过程中的变量
select sum(item_price*quantity) from orderitems
where order_num=onumber into total;
if taxable then
select total+(total/100*taxrate) into total;
end if;
select total into ototal;
end;$$
//调用存储过程
call ordertotal(20005,1,@total);$$
//显示结果
select @total;$$
//删除存储过程
drop procedure ordertotal;

你可能感兴趣的:(存储过程)