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.<
I am using version 6 (MySQL Workbench Community (GPL) for Windows version 6.0.9 revision 11421 build 1170) on Windows Vista. I have no problem with the following options. Probably they fixed it since these guys got the problems three years ago.
/* first option */
SELECT ID
INTO @myvar
FROM party
WHERE Type = 'individual';
-- get the result
select @myvar;
/* second option */
SELECT @myvar:=ID
FROM party
WHERE Type = 'individual';
/* third option. The same as SQL Server does */
SELECT @myvar = ID FROM party WHERE Type = 'individual';
All option above give me a correct result.
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.
It is worth noting that despite the fact that you can SELECT INTO
global variables like:
SELECT ... INTO @XYZ ...
You can NOT use FETCH INTO
global variables like:
FETCH ... INTO @XYZ
Looks like it's not a bug. I hope it will be helpful to someone...
Per the MySQL docs DECLARE works only at the start of a BEGIN...END block as in a stored program.
You maybe miss the @ symbol before your value,like that select 'test' INTO @myValue
;