SELECT INTO Variable in MySQL DECLARE causes syntax error?
I´d like to SELECT a single value into a variable. I´d tried to following:
DECLARE myvar INT(4);
-- immediately returns some syntax error.
SELECT myvalue
FROM mytable
WHERE anothervalue = 1;
-- returns a single integer
SELECT myvalue
INTO myvar
FROM mytable
WHERE anothervalue = 1;
-- does not work, also tried @myvar
Is possible to use DECLARE outside of stored procedures or functions?
Maybe I just dont get the concept of user variables... I just tried:
SELECT myvalue INTO @var FROM `mytable` WHERE uid = 1;
SELECT @var;
...which worked just like it´s supposed to. But if I run each query at a time i just get @var NULL.
Solution 1:
I ran into this same issue, but I think I know what's causing the confusion. If you use MySQL Query Analyzer, you can do this just fine:
SELECT myvalue
INTO @myvar
FROM mytable
WHERE anothervalue = 1;
However, if you put that same query in MySQL Workbench, it will throw a syntax error. I don't know why they would be different, but they are.
To work around the problem in MySQL Workbench, you can rewrite the query like this:
SELECT @myvar:=myvalue
FROM mytable
WHERE anothervalue = 1;
Solution 2:
In the end a stored procedure was the solution for my problem.
Here´s what helped:
DELIMITER //
CREATE PROCEDURE test ()
BEGIN
DECLARE myvar DOUBLE;
SELECT somevalue INTO myvar FROM mytable WHERE uid = 1;
SELECT myvar;
END//
DELIMITER ;
call test();
Solution 3:
These answers don't cover very well MULTIPLE variables.
Doing the inline assignment in a stored procedure causes those results to ALSO be sent back in the resultset. That can be confusing. To using the SELECT...INTO syntax with multiple variables you do:
SELECT a, b INTO @a, @b FROM mytable LIMIT 1;
The SELECT must return only 1 row, hence LIMIT 1, although that isn't always necessary.
Solution 4:
You can also use SET instead of DECLARE
SET @myvar := (SELECT somevalue INTO myvar FROM mytable WHERE uid=1);
SELECT myvar;