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