MySql How to set a local variable in an update statement (Syntax?)

后端 未结 5 1626
[愿得一人]
[愿得一人] 2020-12-24 13:29

How can I set a variable while doing an Update statement? I can\'t seem to figure out the syntax.

So I want something like this below but it\'s saying the syntax is

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 14:07

    If you want to obtain something like this:

    SET @tempVariable := 0; UPDATE myTable SET col1 = 5, col2 = @tempVariable, @tempVariable := 100;

    You can do a trick like this:

    • Create a column value.

    ALTER TABLE Proj ADD col3 numeric;

    • Give a value to col3 in order to set the variable you need (@tempVariable).

    SET @tempVariable := 0; UPDATE myTable SET col1 = 5, col2 = @tempVariable, col3 = @tempVariable := 100;

    • Drop the col3

    ALTER TABLE Proj DROP col3;

    In this way, you can assign values to a variable without change attributes of a table. It is really usefull when setting dinamic values.

    FOR EXAMPLE: @tempVariable := @otherVariable + 100;

提交回复
热议问题