Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE SET one Column to another value and change value in same step

Tags:

tsql

Take the following update statement.

UPDATE  TABLE_1
SET     Units2 = ABS(Units1)
        ,Dollars2=ABS(Dallars1)
        ,Units1 =0
        ,Dollars1 =0
WHERE Units1 < 0
AND   Dollars2 = 0

Here are my questions,

1) Is this legal? It parses and it "seems" to work (on the test table), but will it always work or am I just picking the right records to review.

2) is there a better way to do this.

Thanks,

like image 829
Dayton Brown Avatar asked Sep 15 '11 15:09

Dayton Brown


People also ask

How do you change the value of a column based on another column in SQL?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.

How do I change the value of one column to another column?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

Can we change the value in two columns using a single update query?

We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required.

How update multiple columns with different values in SQL?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.


1 Answers

It is legal, and as long as you are wanting to essentially keep the old values of Units1 and Dollars1 in Units2 and Dollars2 that should work

Here's a test:

CREATE TABLE #Table_1
(
    Units1 INT,
    Dollars1 MONEY,
    Units2 INT,
    Dollars2 MONEY
)
GO

INSERT INTO #Table_1 (Units1, Dollars1, Units2, Dollars2)
VALUES (-1,12.00,3,0.00)
GO

UPDATE  #TABLE_1
SET     Units2 = ABS(Units1)
        ,Dollars2=ABS(Dollars1)
        ,Units1 =0
        ,Dollars1 =0
WHERE Units1 < 0
AND   Dollars2 = 0
GO

SELECT * 
FROM  #Table_1

Outputs:

Units1 | Dollars1 | Units2| Dollars2
0      | 0.00     | 1     | 12.00
like image 195
ericb Avatar answered Sep 21 '22 12:09

ericb