mysql数据存储过程参数实例详解


本文整理自网络,侵删。

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、sqlserver、oracle三大数据库的区别

详解关于mysql查询字符集不匹配问题

如何查看mysql的日志文件

mysql的ddl操作

mysql转储/恢复存储过程和触发器

如何利用mysql数据库判断null结果为1?

mysql 语句执行顺序举例解析

mysql数据查询之子查询

mysql存储过程的优点是什么

mysql中的执行计划explain详解

更多相关阅读请进入《mysql》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...