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


在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;

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM