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;

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

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

  可以采用下列方法进行解决:

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

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

原文地址:https://www.cnblogs.com/xiaobingqianrui/p/10027665.html