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)
未完待续