天天看点

mysql数据库存储过程

存储过程可以简单理解为一条或者多条sql语句的集合,存储过程用来实现将一组关于表的操作的sql语句当作一个整体来执行,存储过程在实际应用中最主要的特点的事提高执行效率以及sql代码封装功能,特别是sql代码封装功能,如果没有存储过程,在外部程序访问数据库时(例如php),要组织很多sql语句,特别是业务逻辑比较复杂的时候,一大堆的sql和条件夹在php代码中,让人不寒而栗,有了sql存储过程,业务逻辑可以封装存储过程,这样不仅容易维护,而且执行效率也高。

例如:在电子商务站点中使用存储过程来实现商品订单处理

存储过程如何一门程序设计语言,同样包含了数据类型,流程控制,输入和输出和它自己的函数库

基本语法

Create procedure sp_nane()  函数里面可以有参数也可以没有

Begin

---------  //代码体

End

Call  sp_nane() 存储过程名  //调用存储过程

实例mysql>use mysql

Mysql>Delimiter $$ //定义分隔符

Mysql>Create procedure sp_nane()  函数里面可以有参数也可以没有

Select user from user;

End$$

Mysql>Delimiter;

方法一show procedure status

实例:show procedure status \G

方法二查看系统表information_schema.routines

实例:select * from information_schema.routines\G

方法三通过show crerate procedure语句查看存储过程定义信息

实例:show crerate procedure proce_user\G

Drop procedure 存储过程名字  删的时候不要加().

实例:drop procedure proce_param_inout;

循环控制

WHILE ---DO--END WHILE  //先判断再执行

实例:

Mysql>create table t1(id int);

Mysql>Create procedure proce_while()  函数里面可以有参数也可以没有

Declare i int;  //定义变量

Set i=1;  //将变量做了一个初始化,如果不做初始化,将为null

While i<5 do

Insert into t1 values(i);

Set i=i+1;

End while;

Pepeat---until end pepeat  先执行再判断

Mysql>Create procedure proce_repeat()  函数里面可以有参数也可以没有

Declare i int default 1;  //定义变量,初始化

repeat  

Until i>=6

End repeat;

Loop--end loop

Mysql>Create procedure proce_loop()  函数里面可以有参数也可以没有

Loop_label:loop   //定义一个标号,跟标签一样

If  i>=6 then

Leave loop_label;  

End if;

End loop;

Mysql>Create procedure proce_param_in(in id int) //用in传值传的是id字段,int类型的

If (id is null) then  //如果id变量是空值

Select ‘id is null’  as id_null;  

Else

Select id as id_inside; //打印一下id的值

Mysql>Create procedure proce_param_out(out id int) //用out传值传的是id字段,int类型的

Select id  as id_inside_1;  //id初始值为null

If (id is not null) then  //如果id变量不是空值

Set id=id+1;

Select id as id_inside_2; //打印一下id的值

Select 100 into id;  //把100输入到id

Select id as id_inside_3;

Mysql>Create procedure proce_param_inout(inout id int) //用out传值传的是id字段,int类型的

Select id  as id_inside_1;  //id值为调用者传进来的值

本文转自    探花无情   51CTO博客,原文链接:http://blog.51cto.com/983865387/1917421