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

1. 为何使用存储过程?

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

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

(3)提升性能,由于使用存储过程比使用单独的SQL语句要快安全

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

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

2. 建立存储过程

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

  调用:spa

  call product_price()命令行

  输出:3d

  

 是否是很简单,下面使用返回值建立存储过程code

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

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

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;

4. 对于使用mysql命令行进程存储操做的补充

  因为mysql命令行使用;做为语句分隔符,若是命令行要解析存储过程的;字符,则它们最终不会成为存储过程的成分,这会使存储过程当中的sql出现句法错误。

  能够采用下列方法进行解决:

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

  DELIMITER // 告诉命令行实用程序使用//做为新的语句结束分隔符,最后再还原为DELIMITER ;