MySQL存储过程写法总结

1、创建无参存储过程。

create procedure product()

begin

        select * from user;

end;

一条简单的存储过程创建语句,此时调用的语句为:

call procedure();

##注意,如果是在命令行下编写的话,这样的写法会出现语法错误,即再select 那一句结束

mysql就会进行解释了,此时应该先把结尾符换一下:

delimiter //

create procedure product()

begin

        select * from user;

end //

最后再换回来

delimiter ;


2、创建有参存储过程

有参的存储包括两种参数,

一个是传入参数;

一个是传出参数;

例如一个存储过程:

create procedure procedure2(

out p1 decimal(8,2),

out p2 decimal(8,2),

in p3 int

)

begin
select sum(uid) into p1 from user where order_name = p3;
select avg(uid) into p2 from user ;
end ;

从上面sql语句可以看出,p1和p2是用来检索并且传出去的值,而p3则是必须有调用这传入的具体值。

看具体调用过程:

call product();    //无参

call procedure2(@userSum,@userAvg,201708);    //有参


当用完后,可以直接查询userSum和userAvg的值:

select @userSum, @userAvg;

结果如下:

+----------+----------+
| @userSum | @userAvg |
+----------+----------+
|    67.00 |     6.09 |
+----------+----------+
1 row in set (0.00 sec)


3、删除存储过程

一条语句: drop procedure product;   //没有括号后面


4、一段完整的存储过程实例:

-- Name: drdertotal
-- Parameters : onumber = order number
--              taxable = 0 if not taxable,1if taxable
--              ototal = order total variable

create procedure ordertotal(
in onumber int,
in taxable boolean,
out ototal decimal(8,2)
) commit 'Obtain order total, optionally adding tax' 
begin
	-- Declare variable for total
	declare total decimal(8,2);
	-- Declare tax percentage
	declare taxrate int default 6;
	
	--Get the order total
	select Sum(item_price*quantity)
	from orderitems
	where order_num = onumber
	into total;
	
	--Is this taxable?
	if taxable then
		--Yes, so add taxrate to the total
		select total+(total/100*taxrate) into total;
	end if;
	
	--Add finally, save to out variable
	select total into ototal;
end;

上面存储过程类似于高级语言的业务处理,看懂还是不难的,注意写法细节

commit关键字:它不是必需的,但如果给出,将在show procedure status的结果中给出。

if语句:这个例子给出了mysqlif语句的基本用法,if语句还支持elseif和else子句。


通过show procedure status可以列出所有的存储过程的详细列表,并且可以在后面加一个

like+指定过滤模式来进行过滤。






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值