Creating Dynamic Query in Stored Procedure MySQL

我是研究僧i 提交于 2019-12-03 09:11:47

You're concatenating the pArea parameter into the SQL unquoted. That is, the content of @Query that you prepare for execution is:

SELECT PinCode FROM Areas WHERE AreaName = Teynampet

Since Teynampet is unquoted, it is parsed as a(n unknown) SQL identifier rather than a string. You should either:

  • quote it in your SQL:

    SET @City  = CONCAT(' WHERE AreaName = ', QUOTE(pArea));
    
  • pass it to the prepared statement as a parameter:

    SET @City  = CONCAT(' WHERE AreaName = ?');
    SET @param = pArea;
    

    and then:

    EXECUTE stmt USING @param;
    

However, why use prepared statements here? Your procedure can be rewritten as a simple SELECT (which raises the question of whether you need to use a stored procedure at all):

CREATE PROCEDURE mp_test(IN pArea VARCHAR(255))
  SELECT PinCode FROM Areas WHERE pArea IN (AreaName, '');

(Note that I'd recommend you use NULL instead of the empty string '', in which case the above test would be pArea IS NULL OR pArea = AreaName).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!