写一个存储过程:
牧牛遛马对存储过程的理解:在自定义函数的基础上,返回的类型是固定的且是单一的,而存储过程实现了参数的来回调用,可以是存储过程内容使用(参数前面定义in),也可以返回到外部查询(参数前面定义out),存储过程比自定义函数的功能要强大很多.
我们实现一个名为遛马的存储过程功能,procedure遛马(a,b)
{
a = 1, b表示订餐;
a = 2, b表示结单;
a = 3, b表示退出系统;
}
surfing the code…
drop procedure if exists liuma;
delimiter $$
create procedure liuma(in a int(5),out b varchar(50))
begin
declare x int(5);
select a into x;
if(x = 1)
then set b:= "订餐";
elseif(x = 2)
then set b:= "结单";
elseif(x = 3)
then set b:= "退出";
end if;
end$$
delimiter ;
运行一下上面的代码
mysql> drop procedure if exists liuma;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> delimiter $$
mysql> create procedure liuma(in a int(5),out b varchar(50))
-> begin
-> declare x int(5);
-> select a into x;
-> if(x = 1)
-> then set b:= "订餐";
-> elseif(x = 2)
-> then set b:= "结单";
-> elseif(x = 3)
-> then set b:= "退出";
-> end if;
-> end$$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql>
mysql>
mysql> set @lm = "";
Query OK, 0 rows affected (0.00 sec)
mysql> call liuma(3,@lm);
Query OK, 1 row affected (0.00 sec)
mysql> select @lm;
+------+
| @lm |
+------+
| 退出 |
+------+
1 row in set (0.00 sec)
mysql> call liuma(1,@lm);
Query OK, 1 row affected (0.00 sec)
mysql> select @lm;
+------+
| @lm |
+------+
| 订餐 |
+------+
1 row in set (0.00 sec)
mysql> call liuma(2,@lm);
Query OK, 1 row affected (0.00 sec)
mysql> select @lm;
+------+
| @lm |
+------+
| 结单 |
+------+
1 row in set (0.00 sec)
存储过程的思想基础的大概理解就是这样,在应用的过程中需要结合实际的逻辑,判断变化的参数及我们是否需要自定义一个存储过程实现相关的功能。