MySQL: Prepare/Execute 在过程中(concat)

MySQL: Prepare/Execute in procedure (concat)

我有点迷路了,希望得到你的帮助。我目前正在学习使用 Mysql,我得到了这个程序:

delimiter //
drop procedure price_update2 //
create procedure price_update2()
BEGIN
DECLARE n INT default 0;
DECLARE i INT default 1;
DECLARE cond varchar(255) default '';

SET cond = CONCAT('SELECT customer_id FROM customers LIMIT ',i,',1');
prepare stt FROM cond;
execute stt;
END //

出于某种原因,我总是在 "cond; execute stt...." 附近遇到错误。可能这只是一件容易的事,但我找不到它。 也尝试过不连接:

delimiter //
drop procedure price_update2 //
create procedure price_update2()
BEGIN
DECLARE n INT default 0;
DECLARE i INT default 1;
DECLARE cond varchar(255) default '';

SET cond = 'SELECT customer_id FROM customers LIMIT 1';
prepare stt FROM cond;
execute stt;
END //

如果我直接使用语句,它工作正常。

这是一件奇怪的事情,但此时你需要使用user-defined variables

delimiter //
drop procedure price_update2 //
create procedure price_update2()
BEGIN
DECLARE n INT default 0;
DECLARE i INT default 1;

SET @cond = CONCAT('SELECT customer_id FROM customers LIMIT ',i,',1');
prepare stt FROM @cond;
execute stt;
DEALLOCATE PREPARE stt; # don't forget to deallocate
END //

manual 指出:

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