---
title: "如何在数据库中使用存储过程"
author: "Even521"
date: "2014-11-05T11:41:14Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2014-11-05T11:41:14Z"
id: 2152545
url: "https://even521.iteye.com/blog/2152545"
---

1.什么是存储过程？

简单地说，存储过程就是数据库中保存的一些sql命令的集合，也可以将其看作互相间有关系sql命令组织在一起的小程序月。

2.使用存储过程的好处？

(1)提高执性行性能。

    通常在客户端执行sql命令时，在数据库中有解析到编译的这个前期准备过程。但是存储过程事先完成了解析、编译的处理后保存在数据库中的，执行减轻数据库的负担，提高执行性能。

(2)可以减轻网络负担。

(3)防止对表的直接访问。

(4)可将数据库的处理黑匣子化。

注意存储过程的功能也是在mysql 5.0以后才被支持。

2.定义存储过程：

创建存储过程语法：create procedure 存储过程名（

                                                        参数的种类1 参数1 数据类型1，..参数种类n 参数n 数据类型n）

                               begin

                                 处理内容

                              end；

例如：对customer 的姓名列 name进行模糊查询，显示customer的所有数据。

delimiter  //

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

//

delimiter;

 

通过delimiter命令改变分隔符

3.存储过程中也可以使用控制语句

if 条件表达式1

   条件表达式1 为ture执行

else if 条件表达式n

条件表达式n 为true执行的命令

else

全部为false 时执行

end if

多重分支：

case 表达式1

   when 值 1 then 表达式=值1 时执行

    when 值n then 表达式=值n 时执行

else

   上述以外时执行

end case

 

循环控制

pereat

知道条件表达式为true 时候执行的命令

until

条件表达式

end pereat

 

循环控制：

while 条件表达式 do

系命令

end while

 

4.确认数据库中存储过程

show procedure status\\G

 

5.调用存储过程：

call sp\_search\_customer('王%')；