在 CREATE PROCEDURE 中使用 DECLARE 和准备语句的语法错误
Syntax Error on using DECLARE and prepared statement inside CREATE PROCEDURE
我正在尝试在存储过程中使用 MySQL 准备好的语句。我已经尝试调试这个 CREATE 代码几个小时了,现在很沮丧。
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 ;
它正在抛出各种 "syntax" 错误。更糟糕的是,确切的错误消息似乎在 phpMyAdmin 和 MySQL 控制台之间有所不同。
拜托谁帮我找出语法错误。
谢谢。
PS:进一步测试后...
这似乎有效:
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 ;
唯一的区别是在第一种形式中使用 @variable
与 DECLARE
。嗯,那么这里的 DECLARE
有什么问题?
原因是
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;
在第一种情况下
DECLARE str1 TEXT DEFAULT '';
SET str1 = CONCAT("SELECT * FROM ", tblname);
str1
的范围是局部的。所以 mysql 抛出错误,你需要使用 User-Defined Variables ,你在第二种情况下使用会话范围。
我正在尝试在存储过程中使用 MySQL 准备好的语句。我已经尝试调试这个 CREATE 代码几个小时了,现在很沮丧。
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 ;
它正在抛出各种 "syntax" 错误。更糟糕的是,确切的错误消息似乎在 phpMyAdmin 和 MySQL 控制台之间有所不同。
拜托谁帮我找出语法错误。
谢谢。
PS:进一步测试后...
这似乎有效:
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 ;
唯一的区别是在第一种形式中使用 @variable
与 DECLARE
。嗯,那么这里的 DECLARE
有什么问题?
原因是
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;
在第一种情况下
DECLARE str1 TEXT DEFAULT '';
SET str1 = CONCAT("SELECT * FROM ", tblname);
str1
的范围是局部的。所以 mysql 抛出错误,你需要使用 User-Defined Variables ,你在第二种情况下使用会话范围。