MySQL将返回值分配给变量

时间:2012-01-09 11:31:23

标签: mysql

如何声明变量并设置一个值,该值是稍后从查询中返回的值。

示例存储过程:

DELIMITER $$

CREATE PROCEDURE `sampledb`.`SetVariableEx`()

    BEGIN

        -- declare variable
        DECLARE xVarA INT;                
        DECLARE xVarB INT;      

        -- in this line, i would like to set a value on xVarA which is a COUNT
        -- of record from table SINGLETABLE
        -- i am getting error on this line.
        SELECT xVarA := COUNT(*) FROM SingleTable;

        -- the value of xVarA is added by 1 and set it to xVarB
        SET xVarB = xVarA + 1;

        -- insert the value of xVarB to the table SINGLETABLE
        INSERT INTO SingleTable(SingleColumn) VALUES (xVarB);

        -- lastly, display all records.
        SELECT * FROM SingleTable;

    END$$

DELIMITER ;

我该怎么做?

1 个答案:

答案 0 :(得分:2)

尝试以下方法:

SET xVarA := (SELECT COUNT(*) FROM SingleTable);

但是,对于此示例,您是否考虑过using an auto auto-incrementing value,而不是自己管理该值?