Syntax Error on using DECLARE and prepared stateme

2019-09-18 01:54发布

问题:

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.