I have a table col1 float, col2 float with the following data:
1,2
3,4
After the query:
UPDATE MyTable SET col1 = 100, col2 = col1
is executed, the rows are:
100,1
100,3
Obviously, the old, not updated value of col1 is used, when col2 is being updated. Is it possible to update the col2 with the new value, referring col1 or I have to write the value (100) twice? I want to use auto-generated queries and it's easier to keep formulas.
Regards,
Here's another alternative to try:
or:
OPTION (MAXDOP 1)
is there to ensure the sequential order of evaluation of assignments.Why don't you use a scalar function? That way you can encapuslate your code into one place and call it for each column you wish to update. You can even pass in paramaters to it.
Then you do this:
Your
UPDATE
statement sees the before version of the row, not the after version. If you're auto-generating queries, isn't it just as easy to have the code dump the formula twice, as it is to pick some other column to reference? Then again, what is the point of storing the same value twice? You could always generate twoUPDATE
statements too as an alternative.You could always have your code generate two update statements:
But then if your queries are actually realistic and you have a
WHERE
clause, you have to repeat theWHERE
clause twice, so you haven't really gained anything.You can do the calculation in a
cross apply
and use the value in the update to avoid adding the same logic in more than one place.