26、MySQL存储过程

1、什么是存储过程,为什么要使用

a、订单处理,库存核实
b、供应商进货
c、入库退库
多组sql语句的组合,构成了一个业务逻辑,这个业务逻辑就是存储过程
简化逻辑,封装业务,安全隔离
2、创建存储过程

mysql> create procedure avg_price() begin select avg(prod_price) from products; end
    -> ;
Query OK, 0 rows affected (0.02 sec)

mysql> call avg_price()
    -> ;
+-----------------+
| avg(prod_price) |
+-----------------+
| 16.133571       |
+-----------------+
1 row in set (0.05 sec)

Query OK, 0 rows affected (0.02 sec)

加上界定符 delimiter //

mysql> delimiter //
mysql> create procedure avg_price() begin select avg(prod_price) from products;
    -> end //
Query OK, 0 rows affected (0.02 sec)

mysql> call avg_price();
    -> //
+-----------------+
| avg(prod_price) |
+-----------------+
| 16.133571       |
+-----------------+
1 row in set (0.08 sec)

Query OK, 0 rows affected (0.02 sec)

mysql>

执行存储过程

mysql> call avg_price()

删除存储过程

mysql> drop procedure avg_price;
Query OK, 0 rows affected (0.02 sec)

5、创建带有参数的存储过程,带有输出

mysql> create procedure price(out pa decimal(8,2),out ph decimal(8,2), out pl decimal(8,2)) begin select avg(prod_price) into pa from products; select max(prod_price) into ph from products; select min(prod_price) into pl from products; end; //

执行

mysql> call price(@p1, @p2, @p3);
    -> select @p1;
    -> //
Query OK, 1 row affected (0.02 sec)

+-------+
| @p1   |
+-------+
| 16.13 |
+-------+

7、带有输入、输出的存储过程

mysql> create procedure pro(in onumber int, out ototal decimal(8,2)) begin select sum(item_price * quantity) from orderitems where order_mum = onumber into ototal;
    -> end; //

执行

delimiter //
create procedure abc(
in num int, 
out total decimal(8, 2)
)
begin
select sum(item_price*quantity) from
orderitems where order_num = num into total;
end //
delimiter ;

执行

mysql> call abc(20007, @p1);
Query OK, 1 row affected (0.02 sec)

mysql> select @p1;
+---------+
| @p1     |
+---------+
| 1000.00 |
+---------+
1 row in set (0.06 sec)

未完待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值