MySQL存储过程写法总结

来源:互联网 发布:如何投诉淘宝平台 编辑:程序博客网 时间:2024/05/20 07:53

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 variablecreate procedure ordertotal(in onumber int,in taxable boolean,out ototal decimal(8,2)) commit 'Obtain order total, optionally adding tax' begin-- Declare variable for totaldeclare total decimal(8,2);-- Declare tax percentagedeclare taxrate int default 6;--Get the order totalselect Sum(item_price*quantity)from orderitemswhere order_num = onumberinto total;--Is this taxable?if taxable then--Yes, so add taxrate to the totalselect total+(total/100*taxrate) into total;end if;--Add finally, save to out variableselect total into ototal;end;

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

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

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


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

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






原创粉丝点击