MySQL如何在存储过程中的PREPARE和EXECUTE之后获得结果?

时间:2011-08-08 19:03:51

标签: mysql variables variable-assignment execute procedures

我目前的代码是:

DELIMITER \\

CREATE PROCEDURE sample (IN _car VARCHAR(15))
    BEGIN
        DECLARE _a INTEGER;
        SET @s = CONCAT('SELECT COUNT(*) FROM train WHERE ', _car, '<=0;');
        PREPARE stmt1 FROM @s;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;

END\\

但我想把SELECT语句的答案捕获到我的_a变量。

我尝试将代码更改为

SET @s = CONCAT('SELECT COUNT(*) INTO', _a,' FROM train WHERE ', _car, '<=0;');

但那没用。

请帮帮忙?

解决!

DELIMITER \\

CREATE PROCEDURE sample (IN _car VARCHAR(15))
    BEGIN
        DECLARE _a INTEGER;
        SET @var = NULL;
        SET @s = CONCAT('SELECT COUNT(*) INTO @var FROM train WHERE ', _car, '<=0;');
        PREPARE stmt1 FROM @s;
        EXECUTE stmt1;
        SELECT @var;
        DEALLOCATE PREPARE stmt1;
END\\

:d

1 个答案:

答案 0 :(得分:2)

如上所述here,您需要在原始语句声明中包含变量赋值。所以你的陈述是这样的:

SELECT COUNT(*) FROM train WHERE ?<=0 INTO _a

然后你将用:

执行它
EXECUTE stmt1 using _car;

获得结果:

select _a;

让我知道它是否有效。