使用Prepared Statement的MySQL存储过程不起作用

时间:2014-11-03 08:37:09

标签: mysql stored-procedures prepared-statement

我有以下存储过程:

CREATE PROCEDURE getLastValueAutomaticShelter(IN fieldName varchar(30), position_number INT)
BEGIN
SET @query = CONCAT('SELECT * FROM automatic_changes WHERE',fieldName,'IS NOT NULL AND P_id=?');
PREPARE stmt FROM @query;
SET @position_number=position_number;
EXECUTE stmt USING @position_number;
DEALLOCATE PREPARE stmt;
END

然后我正在运行它:

mysql> call getLastValueAutomaticShelter('current_level', 500)//

收到以下错误:

ERROR 1064 (42000): 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 'NOT N
ULL AND P_id=?' at line 1

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:2)

你需要在那里添加一些空格:

SET @query = CONCAT('SELECT * FROM automatic_changes WHERE ',fieldName,' IS NOT NULL AND P_id=?');
/*                                                  right ^ here....and ^ here*/

否则您的最终查询可能如下所示:

SELECT * FROM automatic_changes WHEREcolumnameIS NOT NULL AND P_id='whatever';

你明白了这一点:)