SELECT INTO Variable in MySQL DECLARE causes syntax error?

前端 未结 11 2079
無奈伤痛
無奈伤痛 2020-11-30 21:48

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.<

相关标签:
11条回答
  • 2020-11-30 22:19

    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.

    0 讨论(0)
  • 2020-11-30 22:28

    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.

    0 讨论(0)
  • 2020-11-30 22:29

    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...

    0 讨论(0)
  • 2020-11-30 22:30

    Per the MySQL docs DECLARE works only at the start of a BEGIN...END block as in a stored program.

    0 讨论(0)
  • 2020-11-30 22:30

    You maybe miss the @ symbol before your value,like that select 'test' INTO @myValue;

    0 讨论(0)
提交回复
热议问题