SELECT INTO Variable in MySQL DECLARE causes syntax error?

前端 未结 11 2078
無奈伤痛
無奈伤痛 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:05

    You don't need to DECLARE a variable in MySQL. A variable's type is determined automatically when it is first assigned a value. Its type can be one of: integer, decimal, floating-point, binary or nonbinary string, or NULL value. See the User-Defined Variables documentation for more information:

    http://dev.mysql.com/doc/refman/5.0/en/user-variables.html

    You can use SELECT ... INTO to assign columns to a variable:

    http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html

    Example:

    mysql> SELECT 1 INTO @var;
    Query OK, 1 row affected (0.00 sec)
    
    mysql> SELECT @var;
    +------+
    | @var |
    +------+
    | 1    |
    +------+
    1 row in set (0.00 sec)
    
    0 讨论(0)
  • 2020-11-30 22:08

    SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,... FROM table_name WHERE condition;

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

    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;
    
    0 讨论(0)
  • 2020-11-30 22:12

    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 ();
    
    0 讨论(0)
  • 2020-11-30 22:14

    You can also use SET instead of DECLARE

    SET @myvar := (SELECT somevalue INTO myvar FROM mytable WHERE uid=1);
    
    SELECT myvar;
    
    0 讨论(0)
  • 2020-11-30 22:14

    For those running in such issues right now, just try to put an alias for the table, this should the trick, e.g:

    SELECT myvalue 
      INTO myvar 
      FROM mytable x
     WHERE x.anothervalue = 1;
    

    It worked for me.

    Cheers.

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