2014-11-03 68 views
0

我有以下存儲過程:MySQL的存儲過程預處理語句不工作

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 

任何想法?謝謝。

回答

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

你的想法:)

+0

謝謝配合:) – MichalB 2014-11-03 09:38:24