MySQL 预储程序参数用法in, out, inout

2013-02-20_095842

这是MySQL 5实力养成暨评量里的8-25.‘在预储程序中下列哪些指令可用来指定参数传递的方式?’

答案是:(A)IN (B)OUT (C) INOUT

[adsense][/adsense]

ㄚ琪查到了范荣生的MySQL 存储过程参数用法in, out, inout不过是简体文,ㄚ琪把它转成繁体的让朋友们可以较清楚:

MySQL 预储程序参数有三种类型:in、out、inout。它们各有什么作用和特点呢?

一、MySQL 预储程序参数(in)

MySQL 预储程序“in” 参数:跟C 语言的函数参数的值传递类似, MySQL 预储程序内部可能会修改此参数,但对in 类型参数的修改,对呼叫者(caller)来说是不可见的( not visible)。

drop procedure if exists pr_param_in;
create procedure pr_param_in
(
in id int -- in 类型的MySQL 预储程序参数
)
begin
if (id is not null) then
set id = id + 1;
end if;
select id as id_inner;
end;
set @id = 10;
call pr_param_in(@id);
select @id as id_out;
mysql> call pr_param_in(@id);
+----------+
| id_inner |
+----------+
| 11 |
+----------+
mysql> select @id as id_out;
+--------+
| id_out |
+--------+
| 10 |
+--------+

可以看到:用户变数@id 传入值为10,执行预储程序后,在过程内部值为:11(id_inner),但外部变值依旧为:10(id_out)。

二、MySQL 预储程序参数(out)

MySQL 预储程序“out” 参数:从预储程序内部传值给呼叫者。在预储程序内部,该参数初始值为null,无论呼叫者是否给预储程序参数设置值。

drop procedure if exists pr_param_out;
create procedure pr_param_out
(
out id int
)
begin
select id as id_inner_1; -- id 初始值为null
if (id is not null) then
set id = id + 1;
select id as id_inner_2;
else
select 1 into id;
end if;
select id as id_inner_3;
end;
set @id = 10;
call pr_param_out(@id);
select @id as id_out;
mysql> set @id = 10;
mysql>
mysql> call pr_param_out(@id);
+------------+
| id_inner_1 |
+------------+
| NULL |
+------------+
+------------+
| id_inner_3 |
+------------+
| 1 |
+------------+
mysql> select @id as id_out;
+--------+
| id_out |
+--------+
| 1 |
+--------+

可以看出,虽然我们设置了用户定义变数@id 为10,传递@id 给预储程序后,在预储程序内部,id 的初始值总是null(id_inner_1)。最后id 值(id_out = 1)传回给呼叫者。

三、MySQL 预储程序参数(inout)

MySQL 预储程序inout 参数跟out 类似,都可以从预储程序内部传值给呼叫者。不同的是:呼叫者还可以通过inout 参数传递值给预储程序。

drop procedure if exists pr_param_inout;
create procedure pr_param_inout
(
inout id int
)
begin
select id as id_inner_1; -- id 值为呼叫者传进来的值
if (id is not null) then
set id = id + 1;
select id as id_inner_2;
else
select 1 into id;
end if;
select id as id_inner_3;
end;
set @id = 10;
call pr_param_inout(@id);
select @id as id_out;
mysql> set @id = 10;
mysql>
mysql> call pr_param_inout(@id);
+------------+
| id_inner_1 |
+------------+
| 10 |
+------------+
+------------+
| id_inner_2 |
+------------+
| 11 |
+------------+
+------------+
| id_inner_3 |
+------------+
| 11 |
+------------+
mysql>
mysql> select @id as id_out;
+--------+
| id_out |
+--------+
| 11 |
+--------+

从结果可以看出:我们把@id(10),传给预储程序后,预储程序最后又把计算结果值11(id_inner_3)传回给呼叫者。MySQL 预储程序inout 参数的行为跟C 语言函数中的引用传值类似。

通过以上例子:如果仅仅想把数据传给MySQL 预储程序,那就使用“in” 类型参数;如果仅仅从MySQL 预储程序返回值,那就使用“out” 类型参数;如果需要把数据传给MySQL 预储程序,还要经过一些计算后再传回给我们,此时,要使用“inout” 类型参数。

在MySQL英文手册可以参阅MySQL 5.6 Reference Manual :: 13 SQL Statement Syntax :: 13.1 Data Definition Statements :: 13.1.12 CREATE PROCEDURE and CREATE FUNCTION Syntax

简体中文手册可以参阅MySQL 5.1参考手册 :: 20. 存储程序和函数

Comments are closed.