Syntax Error on using DECLARE and prepared statement inside CREATE PROCEDURE

醉酒当歌 提交于 2019-12-12 05:28:58

问题


I am trying to work with MySQL prepared statements inside of a stored procedure. I have been trying to debug this CREATE code for a couple of hours, now frustrated.

DELIMITER //
DROP PROCEDURE IF EXISTS doSomething//
CREATE PROCEDURE doSomething(IN tblname CHAR(32))
BEGIN
    DECLARE str1 TEXT DEFAULT '';
    SET str1 = CONCAT("SELECT * FROM ", tblname);
    PREPARE stmt1 FROM str1;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;
END//
DELIMITER ;

It is throwing up all sorts of "syntax" errors. Worse still, the exact error message seems to vary between phpMyAdmin and the MySQL Console.

Please, someone, help me pinpoint the syntax error.

Thank you.

PS: After Further Testing...

This seems to work:

DELIMITER //
DROP PROCEDURE IF EXISTS doSomething//
CREATE PROCEDURE doSomething(IN tblname CHAR(32))
BEGIN
    SET @str1 = CONCAT("SELECT * FROM ", tblname);
    PREPARE stmt1 FROM @str1;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;
END//
DELIMITER ;

And the only difference is the use of @variable vs DECLARE in the first form. Hmmm, so what's wrong with DECLARE here?


回答1:


The reason is

A statement prepared in stored program context cannot refer to stored procedure or function parameters or local variables because they go out of scope when the program ends and would be unavailable were the statement to be executed later outside the program. As a workaround, refer instead to user-defined variables, which also have session scope;

In the first case the

DECLARE str1 TEXT DEFAULT '';
SET str1 = CONCAT("SELECT * FROM ", tblname);

The scope of str1 is local. So mysql is throwing the error and you need to use User-Defined Variables , which you are doing in the 2nd case with the session scope.



来源:https://stackoverflow.com/questions/28985362/syntax-error-on-using-declare-and-prepared-statement-inside-create-procedure

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