MySql必知必会实战练习(五)存储过程

1. 为什么使用存储过程?

(1) 通过把处理封装在容易使用的单元中,简化复杂操作

(2) 为了保证数据的完整性,不要求反复建立一系列的处理操作,所有开发人员和应用程序都使用同一(试验和测试)存储过程,则所使用的代码否的相同的,这一点的延申就是为了防止错误,保证数据的一致性

(3)提高性能,因为使用存储过程比使用单独的SQL语句要快

(4)存储功能可以编写功能更强更灵活的代码

  一句话,既简单、安全又高性能

2. 创建存储过程

create procedure product_price()
begin
    select Avg(proc_price) as priceaverage
    from products;
end;

  调用:

  call product_price()

  输出:

  

 是不是很简单,下面使用返回值创建存储过程

drop procedure product_price;
create procedure product_price(
    OUT pa decimal(8,2)
)
begin
    select Avg(proc_price) into pa
    from products;
end;

call product_price(@priceaverge);
select @priceaverge

  下面是参数和返回值创建存储过程

drop procedure IF EXISTS product_price;
create procedure product_price(
    IN number int,
    OUT sum decimal(8,2)
)
begin
    select Sum(proc_price) into sum
    from products 
    where vend_id = number;
end;

call product_price(1003, @pricesum);
select @pricesum;

3. 复杂存储过程展示

  使用先前创建的orderitems表

  

  需求:

  通过order_num计算该订单号的产品总价,再根据是否交税情况返回最终价格

create procedure orderprice(
    in ordernum int,
    in istax boolean,
    out sumprice decimal(8,2)
)
begin
    declare taxrate int default 6;
    select Sum(quantity * item_price) into sumprice
    from orderitems
    where order_num = ordernum;
    
    if istax then
        select sumprice+(sumprice*taxrate/100) into sumprice;
    end if;
end;

  测试:

call orderprice(20005,0,@sumprice);
select @sumprice;

call orderprice(20005,1,@sumprice);
select @sumprice;

猜你喜欢

转载自www.cnblogs.com/xiaobingqianrui/p/10027665.html