什么是存储过程?
存储过程就是把复杂的一系列操作,封装成一个过程。类似于shell,python脚本等。
存储过程的优缺点
优点是:
1)复杂操作,调用简单
2)速度快缺点是:
1)封装复杂
2) 没有灵活性
创建存储过程语法:
create procedure 名称 (参数....)
begin
过程体;
过程体;
end
参数:in|out|inout 参数名称 类型(长度)
in:表示调用者向过程传入值(传入值可以是字面量或变量)
out:表示过程向调用者传出值(可以返回多个值)(传出值只能是变量)
inout:既表示调用者向过程传入值,又表示过程向调用者传出值(值只能是变量)
声明变量:declare 变量名 类型(长度) default 默认值;
给变量赋值:set @变量名=值;
调用存储命令:call 名称(@变量名);
删除存储过程命令:drop procedure 名称;
查看创建的存储过程命令:
show create procedure 名称;
例子:
外置参数:
mysql> delimiter //
mysql> create procedure theselect(in n int)
begin
select * from employee limit n;
end
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> set @n=5;//
Query OK, 0 rows affected (0.00 sec)
mysql> call theselect(@n);//
+-------+--------+--------+------+------------+----------+--------+
| empno | ename | job | mgr | hiredate | sal | deptnu |
+-------+--------+--------+------+------------+----------+--------+
| 1004 | 猪八戒 | 经理 | 1009 | 2001-04-02 | 29650.00 | 20 |
| 1006 | 猴子 | 经理 | 1009 | 2011-05-01 | 28500.00 | 30 |
| 1007 | 张飞 | 经理 | 1009 | 2011-09-01 | 24500.00 | 10 |
| 1008 | 诸葛亮 | 分析师 | 1004 | 2017-04-19 | 30000.00 | 20 |
| 1013 | 林俊杰 | 分析师 | 1004 | 2011-12-03 | 30000.00 | 20 |
+-------+--------+--------+------+------------+----------+--------+
5 rows in set (0.02 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> drop procedure theselect;//
Query OK, 0 rows affected (0.01 sec)
mysql> call theselect(@n);//
1305 - PROCEDURE test.theselect does not exist
内置参数:
mysql> create procedure theselect()
begin
declare n int default 3;
select * from employee limit n;
end
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> call theselect;
-> //
+-------+--------+------+------+------------+----------+--------+
| empno | ename | job | mgr | hiredate | sal | deptnu |
+-------+--------+------+------+------------+----------+--------+
| 1004 | 猪八戒 | 经理 | 1009 | 2001-04-02 | 29650.00 | 20 |
| 1006 | 猴子 | 经理 | 1009 | 2011-05-01 | 28500.00 | 30 |
| 1007 | 张飞 | 经理 | 1009 | 2011-09-01 | 24500.00 | 10 |
+-------+--------+------+------+------------+----------+--------+
3 rows in set (0.02 sec)
Query OK, 0 rows affected (0.00 sec)