转载地址:http://www.2cto.com/database/201212/177380.html
存储过程简单来说,就是为以后的使用而保存的一条或多条MySQL语句的集合。可将其视为批文件,虽然它们的作用不仅限于批处理。 www.2cto.com
使用存储过程需要MySQL5及以后的版本支持。
一、为什么要使用存储过程
通过把处理封闭在容易使用的单元中,简化复杂的操作;
将一系列处理步骤放到同一存储过程中,保证了数据的完整性和操作的安全性;
简化对变更的管理;
提高性能。使用存储过程比使用单独的SQL语句要快;
存在一些只能用在单个请求中的MySQL元素和特性,存储过程可以使用它们来编写功能更强更灵活的代码;
二、基本操作
1、创建存储过程
CREATE PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ] param_name type
示例:
[sql]
mysql>create procedure sp_test()
->begin
-> select userid,username from newname where userid=215;
->end
->//
2、执行存储过程
CALL sp_name;
示例:
[sql]
mysql> call sp_test();
+--------+----------+
| userid | username |
+--------+----------+
| 215 | NULL |
+--------+----------+
3、删除存储过程
DROP PROCEDURE [ IF EXISTS ] sp_name;
示例:
[sql]
mysql> drop procedure if exists sp_test;
4、查看存储过程创建信息
SHOW CREATE PROCEDURE sp_name;
示例:
[sql]
mysql> show create procedure sp_test;
+-----------+----------+--------------------------------------------------------+----------------------+----------------------+--------------------+
| Procedure | sql_mode | Create Procedure | character_set_client | collation_connection | Database Collation |
+-----------+----------+--------------------------------------------------------+----------------------+----------------------+--------------------+
| sp_test | | CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_test`()
begin
select userid,username from newname where userid=215;
end | latin1 | latin1_swedish_ci | latin1_swedish_ci |
+-----------+----------+--------------------------------------------------------+----------------------+----------------------+--------------------+
5、查看存储过程状态
SHOW PROCEDURE STATUS [ LIKE '' ];
示例:
[sql]
mysql> show procedure status like 'sp_test';
+------+---------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+-
| Db | Name | Type | Definer | Modified | Created | Security_type | Comment | character_set_client |
+------+---------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+-
| test | sp_test | PROCEDURE | root@localhost | 2012-12-17 23:57:38 | 2012-12-17 23:57:38 | DEFINER | | latin1 |
+------+---------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+-
www.2cto.com
6、使用存储过程参数
示例:
[sql]
mysql> delimiter //
mysql> create procedure sp_type_cnt(
-> IN in_type int,
-> OUT out_cnt int
-> )
-> begin
-> select count(*)
-> from newname
-> where type = in_type
-> into out_cnt;
-> end;
-> //
mysql> delimiter ;
mysql> call sp_type_cnt(0,@cnt);
mysql> select @cnt;
+------+
| @cnt |
+------+
| 159 |
+------+