日期:2014-05-16  浏览次数:20834 次

Mysql 存储过程1

存储过程的优势:

1,一般的sql命令在执行前需要解析、编译前提准备过程,但是存储

? ?过程是事先完成了解析,编译处理后保存在数据库的,执行时能减轻

? ?数据库负担,提高执行性能。

2,减轻网络负担,之前的传递sql语句,变成现在的传递参数。

3,防止对表的直接访问。

4,可以减少大部分的程序代码。

5,msyql5.0版本之后才支持存储过程

?

写mysql存储过程需要注意一下几点:

1,要定义delimiter //

2,如果存储过程的参数如果是输入中文的话,要在定义存储过程的后面加上character set gbk这个编码,

? ?不然调用存储过程使用中文参数的时候会出错,

3,如果你的存储过程里边需要模糊查询,用到 like '%内容%' 不要在select 语句的where后边写'%';定义一个参数,

? ?用: set wherestr = "'%"+wherestr+"%'";拼接语句

4,最后要还原结束符:delimiter ; 为;作为语句的结束符

5,存储过程代码中如果包含mysql的扩充功能,那么代码将不能移植。

?

?

存储过程知识点:

1,创建语法

? ?create procedure 存储过程名(

? ? ? 参数种类 ?参数名 参数类型)

? ?begin ?

? ? ? ?处理内容

? ?end

? ?注意:处理内容必须放在begin、end之间,如果仅有一条语句

? ? ? ? ?可以省略begin end 但是强烈建议,所有的都加上begin

end块。养成良好的习惯。

参数种类:in,out,inout 默认的是in可以不写。

?

2,创建存储过程,接收一个收入参数,如果该参数有null或者是''

? ?那么查询customer的全部记录,如果没有上述情况则查询该表中

? ?那么字段为参数的记录。

? ?create procedure sp_search_customer(in p_name varchar(20))

? ?begin

? ? ? ?if p_name is null or p_name = '' ?

? ? ? ?then ?

? ? ? ? ? ? select * from customer;

? ? ? ?else?

? ? ? ? ? ? select * from customer where name like p_name;

? ? ? ?end if;

? ?end

? ?注意:1,判断一个变量是否为空时: p_name is null

? ? ? ? ?2,判断一个变量是否是空字符串是 p_name = '' 等号是单等号

3,end if 要分开,并且要跟上分好,否则他妈的编译不通过。

? ?调用:call sp_search_customer('陈%');//注意这种方式在学习的时候

? ? ? ? ?可以这样调用,实际开发会出现sql注入的bug。

?

3,创建存储过程实现功能:根据name的值查询customer表,并把查询的结果的

? 数返回来。

? create procedure sp_search_customer(in p_name varchar(20),out p_cnt int)

? begin

? ? ?if p_name is null or p_name='' ? then

? ? ? ? select * from customer;

? ? ?else

? ? ? ? select * from customer where name like p_name;

? ? ?end if;

? ? ?select found_rows() into p_cnt;

? end

? 调用:call sp_search_customer('陈超阳%',@num);

? ? ? ? select @num;

? 说明:1,found_rows()函数取得前一条select语句检索出来的记录总数。

? ? ? ? 2, select .....into 命令用于将select语句取得的结果设置到指定的

? 变量中(存储过程中的变量就像是存储数据的临时容器,输入输出参数

? 也是变量的一种。

? select into 语法: