使用存储过程的好处:简单,安全,高性能
23.1 创建存储过程
创建存储过程的一个例子:
delimiter //
create procedure avgpricing()
begin
select avg(price) as averagepricing from products;
end //
delimiter ;
注意,首尾的delimiter语句在命令行下是必要的,否则语句中有两个;会导致报错
23.2 使用存储过程
call avgpricing();
删除存储过程:
drop procedure avgpricing; // 无需带括号了
23.3 带参的存储过程
某个算出最小价格,最大价格,平均价格的语句如下:
delimiter //
create procedure productpricing(
out pl decimal(8,2),
out ph decimal(8,2),
out pa decimal(8,2)
)
begin
select min(prod_price) from products into pl;
select max(prod_price) from products into ph;
select avg(prod_price) from products into pa;
end //
delimiter ;
一个复杂的有输入有输出的存储过程的例子
- 获取总计 2.根据输入确定是否算税 3.返回总计值
create procedure ordertotal(
in onumber int,
in taxable boolean,
out otatal decimal(8,2))
begin
-- declare variables for store local sum
declare total decimal(8,2);
declare taxreate int default 6;
-- get total
select sum(item_price*quantity)
from orderitems
into total
where order_num = onumber;
-- if need tax
if taxable then
select total + total/100*taxrate into total;
-- now we need to set otatal to total
end if;
select total into ototal;
end;
调用上述存储过程的例子:
call ordertotal(20005, 1, @ototal);
select @ototal;
如何看数据库中有哪些存储过程(包含何时创建,由谁创建等信息)
show procedure status;
show procedure statues like "ordertotal";