在mysql中使用select into local变量和prepared语句

时间:2011-10-27 14:23:20

标签: mysql stored-procedures

每次调用此存储过程我都会收到此错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1

什么似乎是问题?

以下是代码:

DELIMITER $$

DROP PROCEDURE IF EXISTS `singledb`.`TOUR_TRANSFER`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `TOUR_TRANSFER`()
BEGIN

BEGIN -- for rubric table
            DECLARE tblRubric_rubric_id INT;
            SET @qry = concat('SELECT count(*) into ',tblRubric_rubric_id,' FROM zerodb2.tour_template');
            PREPARE statement FROM @qry;
            EXECUTE statement;

            SELECT tblRubric_rubric_id;
END;
END$$

DELIMITER ;

2 个答案:

答案 0 :(得分:11)

来自http://bugs.mysql.com/bug.php?id=15263

“参数标记只能在数据值出现的地方使用,而不能用于SQL 关键字,标识符等。“

所以,我们做不到:

PREPARE stmt FROM'SELECT id INTO?从t1';

我们不能用?而不是标识符(变量名)。

当您使用参数名称时:

PREPARE stmt FROM'SELECT id INTO rid FROM t1';

在正在准备的字符串中,然后服务器根本不知道rid指的是什么 您要准备的声明。您可以尝试在SP之外准备它 结果:

的MySQL>准备stmt从'select id into p from t1'; ERROR 1327(42000):未声明的变量:p

所以我只使用了用户变量,见下文:

DROP PROCEDURE IF EXISTS `singledb`.`TOUR_TRANSFER`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `TOUR_TRANSFER`()
BEGIN
BEGIN -- for rubric table
            -- DECLARE @tblRubric_rubric_id INT;

            SET @tblRubric_rubric_id := 0;
            SET @qry = 'SELECT count(*) into @tblRubric_rubric_id FROM zerodb2.tour_template';
            PREPARE statement FROM @qry;
            EXECUTE statement;
END;
END$$

答案 1 :(得分:0)

我认为你有很多语法错误。这通常是我编写存储过程的方式,它们可以工作。到目前为止尝试这个。基本上,如果您要在下一个语句中选择该临时变量,则无需在该临时变量中选择计数。

DELIMITER $$

DROP PROCEDURE IF EXISTS TOUR_TRANSFER;
CREATE PROCEDURE TOUR_TRANSFER()


BEGIN # for rubric table
DECLARE tblRubric_rubric_id INT;

SET @qry := CONCAT('SELECT count(*) FROM zerodb2.tour_template');
PREPARE statement FROM @qry;
EXECUTE statement;

#SELECT tblRubric_rubric_id; # i don't think this will work

END$$

DELIMITER ;