博客
关于我
MySQL 存储过程参数:in、out、inout
阅读量:792 次
发布时间:2023-02-10

本文共 1648 字,大约阅读时间需要 5 分钟。

MySQL 存储过程参数的使用说明

MySQL 存储过程支持三种类型的参数:in、out 和 inout。这些参数类型在传递数据时有不同的行为,理解这些行为对于有效调用存储过程至关重要。本文将详细解释这三种参数类型的特点及其使用方法。

一、in 参数

in 参数类似于 C 语言中的函数参数。在调用存储过程时,调用者可以传递值给存储过程。然而,存储过程在执行过程中可能会修改这些参数的值,但对调用者来说,这些修改是不可见的。例如:

create procedure pr_param_in(in id int);

当调用存储过程时,传递一个整数值:

call pr_param_in(10);

存储过程内部可以修改 id 的值,但调用者无法直接访问修改后的值。

示例
create procedure pr_param_in(in id int)begin    if id is not null then        set id = id + 1;    end if;    select id as id_inner;end;

调用时:

call pr_param_in(10);

执行结果会显示 id_inner 为 11,但 id_out 仍为 10(假设存储过程未修改外部变量)。

二、out 参数

out 参数用于从存储过程返回值给调用者。存储过程执行后,out 参数的值会被传回调用者。初始值为 null,即使调用者未传递值也为 null。

create procedure pr_param_out(out id int);

调用时:

call pr_param_out();

或:

set @id = 10;call pr_param_out();

示例存储过程:

create procedure pr_param_out(out id int)begin    select null as id_inner_1;    if id is not null then        set id = id + 1;    end if;    select id as id_out;end;

调用时:

call pr_param_out();

结果中 id_out 为 1,而 id_inner_1 为 null。

三、inout 参数

inout 参数结合了 in 和 out 的特点。调用者可以通过 inout 参数传递值给存储过程,并且存储过程可以返回修改后的值给调用者。inout 参数的行为类似于 C 语言中的引用传值。

create procedure pr_param_inout(inout id int);

调用时:

call pr_param_inout(10);

示例存储过程:

create procedure pr_param_inout(inout id int)begin    if id is not null then        set id = id + 1;    end if;    select id as id_inner_2;    if id is null then        set id = 1;    end if;    select id as id_inner_3;end;

调用时:

call pr_param_inout(10);

结果中 id_inner_3 为 11,而 id_out 也是 11。

参数默认值

存储过程的参数可以设置默认值,减少调用时的参数传递量。例如:

create or replace procedure procdefault(    p1 varchar2,    p2 varchar2 default 'mark')

此时,调用时只需传递 p1 的值,p2 会使用默认值。

通过以上说明,可以看到不同参数类型的行为差异,并根据需求选择合适的参数类型。

转载地址:http://tkbfk.baihongyu.com/

你可能感兴趣的文章
MySQL 字符串截取函数,字段截取,字符串截取
查看>>
MySQL 存储引擎
查看>>
mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
查看>>
MySQL 存储过程参数:in、out、inout
查看>>
mysql 存储过程每隔一段时间执行一次
查看>>
mysql 存在update不存在insert
查看>>
Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
查看>>
Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
查看>>
Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
查看>>
Mysql 学习总结(89)—— Mysql 库表容量统计
查看>>
mysql 实现主从复制/主从同步
查看>>
mysql 审核_审核MySQL数据库上的登录
查看>>
mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
查看>>
mysql 导入导出大文件
查看>>
MySQL 导出数据
查看>>
mysql 将null转代为0
查看>>
mysql 常用
查看>>
MySQL 常用列类型
查看>>
mysql 常用命令
查看>>
Mysql 常见ALTER TABLE操作
查看>>