创建存储过程
创建一个简单的存储过程
CREATE PROCEDURE mypro() BEGIN SELECT * FROM products; END;
调用存储过程
CALL mypro()
删除存储过程
DROP PROCEDURE IF EXISTS mypro
下面。创建带参数的存储过程,just like function
CREATE PROCEDURE newpro( OUT min DECIMAL(8,2), OUT avg DECIMAL(8,2), OUT max DECIMAL(8,2) ) BEGIN SELECT MIN(item_price) INTO min FROM orderitems; SELECT avg(item_price) INTO avg FROM orderitems; SELECT max(item_price) INTO max FROM orderitems; END;
调用
CALL newpro(@最小,@平均,@最大); SELECT @最小,@平均,@最大;
得到
-----------------------------------------
带参数in的存储过程
CREATE PROCEDURE newproin( IN pro_id int, OUT min DECIMAL(8,2), OUT avg DECIMAL(8,2), OUT max DECIMAL(8,2) ) BEGIN SELECT MIN(item_price) FROM orderitems WHERE orderitems.order_item=pro_id INTO min; SELECT avg(item_price) FROM orderitems WHERE orderitems.order_item=pro_id INTO avg ; SELECT max(item_price) FROM orderitems WHERE orderitems.order_item=pro_id INTO max; END;
调用过程
CALL newproin(4,@最小,@平均,@最大); SELECT @最小,@平均,@最大;
--------------------------------------------
过程中间再复杂点
CREATE PROCEDURE propro( IN pro_id int,--传递进来的商品id IN flag boolean,--是否需要加税 OUT pricetotal DECIMAL(8,2)--返回出去的值 ) BEGIN DECLARE temprice DECIMAL(8,2);--函数内部变量 DECLARE rate int DEFAULT 7;--内部变量税率,千分之七 SELECT SUM(item_price)FROM orderitems WHERE orderitems.order_item=pro_id INTO temprice;--总价into到内部变量中 IF flag THEN--判断是否加税 SELECT temprice+(temprice*(rate*0.001)) INTO temprice; END IF; SELECT temprice INTO pricetotal;--内部变量into到返回出去的变量中 END;
调用依然很简单
CALL propro(3,FALSE,@totalprice); SELECT @totalprice;