视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
MySQL存储过程参数用法in,out,inout_MySQL
2020-11-09 18:14:54 责编:小采
文档


bitsCN.com
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 存储过程参数)beginif (id is not null) thenset 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)beginselect id as id_inner_1; -- id 初始值为 nullif (id is not null) thenset id = id + 1;select id as id_inner_2;elseselect 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)beginselect id as id_inner_1; -- id 值为调用者传进来的值if (id is not null) thenset id = id + 1;select id as id_inner_2;elseselect 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” 类型参数。
作者 crocodile bitsCN.com

下载本文
显示全文
专题