MySQL存储过程把执行结果保存在变量中

本文共 1,003 字,预计阅读时间 3 分钟

在MySQL存储过程中若需要把执行的结果保存在变量中,可以使用into关键字。但使用普通语句和预处理语句的保存方式不一样。

1)普通语句

复制代码
create procedure proc_var02()
begin
    declare create_time datetime;
    select now() into create_time;
    select create_time;
end;
复制代码

普通的语句使用这种方式是没有问题的,可以直接赋值成功。

2)预处理语句

错误写法:

复制代码
create procedure proc_var02()
begin
    declare create_time datetime;
    set @stmt = concat('select now() into', create_time);
        prepare stmt from @stmt;
        execute stmt;
        deallocate prepare stmt;
    select create_time;
end;
复制代码

创建后调用此存储过程,会出现错误

call proc_var02()
> 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1
> 时间: 0s

 

正确写法:

复制代码
create procedure proc_var02()
begin
    set @stmt = concat('select now() into @create_time');
        prepare stmt from @stmt;
        execute stmt;
        deallocate prepare stmt;
    select @create_time;
end;
复制代码

需使用用户变量进行接收,不能使用局部变量。

posted @   钟小嘿  阅读(1413)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示