---
title: "数据库中使用存储过程"
author: "piperzero"
date: "2012-12-20T16:18:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2013-01-07T09:48:18Z"
id: 1764177
url: "https://piperzero.iteye.com/blog/1764177"
---

存储过程就是数据库中保存的一系列SQL命令的集合。

使用存储过程可以减轻数据库负担，提高执行性能、减轻网络负担、可防止对表的直接访问、可将数据库的处理黑匣子化。

**1、定义存储过程：语法【create procedure 存储过程名**

**（参数的种类1 参数1 数据类型1\[，参数的种类2 参数2 数据类型2....]）**

**begin**

**处理内容**

**end】**

如：mysql&gt; delimiter //  
mysql&gt; create procedure sp\_search\_customer(in p\_nam varchar(20))  
\-&gt; begin  
\-&gt; if p\_nam is null or p\_nam='' then  
\-&gt; select * from customer;  
\-&gt; else  
\-&gt; select * from customer where nam like p\_nam;  
\-&gt; end if;  
\-&gt; end  
\-&gt; //

注：delimiter是改变分隔符\[;]，因为MySQL监视器中默认的分隔符是\[;]，存储过程本身含有\[;]，所以为了避免发生歧义，通常用\[//]代替。

**2、确认数据库中的存储过程：语法【show procedure status\\G】**

如：mysql&gt; show procedure status\\G  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** 1. row \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
Db: home  
Name: sp\_search\_customer  
Type: PROCEDURE  
Definer: root@localhost  
Modified: 2012-12-20 15:38:12  
Created: 2012-12-20 15:38:12  
Security\_type: DEFINER  
Comment:  
character\_set\_client: utf8  
collation\_connection: utf8\_general\_ci  
Database Collation: utf8\_general\_ci  
1 row in set (0.01 sec)

**3、确认存储过程的定义：语法【show create procedure 存储过程名\\G】**

如：mysql&gt; show create procedure sp\_search\_customer\\G  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** 1. row \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
Procedure: sp\_search\_customer  
sql\_mode: STRICT\_TRANS\_TABLES,NO\_AUTO\_CREATE\_USER,NO\_ENGINE\_SUBSTITU  
TION  
Create Procedure: CREATE DEFINER=\`root\`@\`localhost\` PROCEDURE \`sp\_search\_cus  
tomer\`(in p\_nam varchar(20))  
begin  
if p\_nam is null or p\_nam='' then  
select * from customer;  
else  
select * from customer where nam like p\_nam;  
end if;  
end  
character\_set\_client: utf8  
collation\_connection: utf8\_general\_ci  
Database Collation: utf8\_general\_ci  
1 row in set (0.01 sec)

**4、执行存储过程：语法【call 存储过程名（参数，...）】**

如：mysql&gt; call sp\_search\_customer('san')\\G  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** 1. row \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
mid: N0008  
nam: san  
birth: 1990-09-23  
sex: 1  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** 2. row \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
mid: N0009  
nam: san  
birth: 1990-09-23  
sex: 0  
2 rows in set (0.00 sec)