1

How do you declare variable and set a value which is a return from a query on them later.

Sample Stored Procedure:

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 ;

how would i do that?

1 Answer 1

3

Try the following:

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

However, for this example, have you considered using an auto auto-incrementing value, rather than managing the value yourself?

Sign up to request clarification or add additional context in comments.

2 Comments

AutoIncrement is not my point in the qestion but rather setting the value from the query to a variable. SET xVarA := SELECT COUNT() FROM SingleTable; does not work but by putting the query inside a Parenthesis works. SET xVarA := (SELECT COUNT() FROM SingleTable); thanks!
@491243 Somehow missed this previously, rather belatedly got round to updating my answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.