如何在MySQL中执行存储在变量中的查询?

时间:2017-04-26 06:23:01

标签: mysql

我正在尝试在sqlyog中执行

的查询
SET @adm_code = 12781;
SET @transfer = (SELECT MAX(id) FROM std_transfer_history AS sth
WHERE admission_code = @adm_code);
EXECUTE @transfer;

但是它会出错

Query: execute @transfer

Error Code: 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 '@transfer' at line 1

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0 sec

那我怎么能摆脱......

1 个答案:

答案 0 :(得分:0)

您缺少执行动态查询的prepare语句。

// your transfer variable query ...

PREPARE stmt FROM @transfer;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;