mysql dynamic query in stored procedure

前端 未结 3 1107
南旧
南旧 2020-11-29 09:01

i am creating a dynamic query in stored procedure. my stored procedure is as follows:

CREATE PROCEDURE `test1`(IN tab_name VARCHAR(40),IN w_team VARCHAR(40))         


        
3条回答
  •  粉色の甜心
    2020-11-29 09:42

    Error Code: 1054. Unknown column 'SPA' in 'where clause'

    This happens when you do not enclose input string within quotes, and SQL engine tries to identify it as a column in the table being queried. But it fails as it can't find it.

    But what happens when it finds such column?
    It fetches results when it finds some matches on the column values.
    Obviously this is not what one was expecting.

    How to overcome this? Use Prepared Statements with dynamic input values.

    You can use placeholders like ? in stored procedures too on dynamic input values to use with Prepared Statements. The engine will handle escape characters and other string values when assigned to or compared within SQL expressions.

    You just need to re-assign procedure inputs to one or more session variables, as required.

    Example on your procedure:

    CREATE PROCEDURE `test1`( IN tab_name VARCHAR(40), IN w_team VARCHAR(40) )
    BEGIN
      SET @t1 = CONCAT( 'SELECT * FROM ', tab_name, ' where team = ?' ); -- <-- placeholder
      SET @w_team := w_team;
    
      PREPARE stmt3 FROM @t1;
      EXECUTE stmt3 USING @w_team; -- <-- input for placeholder
      DEALLOCATE PREPARE stmt3;
    END;
    

提交回复
热议问题