mysql存储过程语法:
create PROCEDURE ‘过程名’(
//参数
)
begin
//sql语法
end;
------------------------------
一、入门实例:
create PROCEDURE demo()
BEGIN
select
AVG(prod_price) as priceaverage
from products;
end;
调用 存储过程:call demo();
删除存储过程:drop PROCEDURE demo;
二、带参数OUT的存储过程:
create PROCEDURE demo(
OUT p1 DECIMAL(8,2),
OUT ph DECIMAL(8,2),
OUT pa DECIMAL(8,2)
)
BEGIN
select min(prod_price)
INTO p1
from products;
select max(prod_price)
INTO ph
from products;
select avg(prod_price)
INTO pa
from products;
END;
关键字:OUT 指出相应的参数用来从存储传出一个值(返回给调用者)
INTO 对存储过程传入和传出。
上面这句话的意思就是,将存储过程中查询出来的三个数值通过 INTO 赋值给存储过程的参数。
使用sql语句:
CALL demo(@pricelow,@pricehigh,@priceaverage);
然后查询:
select @pricelow;
select @pricehigh;
select @priceaverage;
分别查出了定义的三个变量。
三、带参数IN的存储过程:
create PROCEDURE demo_1(
IN onumber INT,
OUT ototal DECIMAL(8,2)
)
BEGIN
SELECT sum(item_price*quantity)
from orderitems
where order_num = onumber
INTO ototal;
END;
关键字: IN:onumber : 被传入存储过程
OUT: 从存储过程返回的合计赋值给 ototal。
INTO: 对存储过程传入和传出 otota。
上面解析sql:通过传递进来的 onumber 作为条件,将查询出来sum 赋值ototal
执行如下语句:
CALL demo_1(20005,@total);
传入参数 20005,将结果复制给total。
select @total
查询结果。
create PROCEDURE demo_2(
IN onumber INT,
IN taxable BOOLEAN,
OUT ototal DECIMAL(8,2)
)
BEGIN
DECLARE total DECIMAL(8,2);
DECLARE taxrate INT DEFAULT 6;
select SUM(item_price*quantity)
from orderitems
where order_num = onumber
INTO total;
IF taxable THEN
select total + (total/100*taxrate) INTO total;
END IF;
select total INTO ototal;
end;
关键字:
IN : 被传入存储过程
OUT :从存储过程返回的参数
INTO :赋值语句
DECLARE:定义变量。需要加变量名和 数据类型。
sql:传入两个条件参数 onumber 和 taxable 。 ototal 作为传出参数。先将查询赋值给total,然后再赋值给ototal。
CALL demo_2(20005,0,@total)
select @total
会查出编号为20005的item_price*quantity 的合计。如果第二个参数不为0,则执行select total + (total/100*taxrate) INTO total.
查询存储过程:
show PROCEDURE STATUS