SELECT INTO Variable in MySQL DECLARE causes syntax error?

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

提交回复
热议问题