Reputation: 181
I am trying to update 3 different columns in a table based on 3 different conditions in the where clause. (I have the updated data in a different table, so I am joining them on the primary keys)
For example, if I did not have a value previously in field1 for a customer but now I do, I should be able to update the column 'field1'. Similarly, I would like to update columns field2 and field3.
Can I accomplish this in a single Update statement.
To Update one column you can write something like this:
Update tblCustomer
SET tblCustomer.Order_Date = tblCustomerInfo.Order_Date
FROM tblCustomer
LEFT JOIN tblCustomerInfo ON (tblCustomer.CustomerID = tblCustomerInfo.CustomerID)
WHERE tblCustomer.Order_Date <> tblCustomerInfo.Order_Date
AND tblCustomer.Order_Date is NULL;
How about updating 3 different Columns in single go based on different where conditions (if the data was missing for that column was missing previously, and is now available)
Upvotes: 11
Views: 38145
Reputation: 256
UPDATE categories
SET display_order = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END,
title = CASE id
WHEN 1 THEN 'New Title 1'
WHEN 2 THEN 'New Title 2'
WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)
Upvotes: 24
Reputation: 358
You can update multiple columns
UPDATE [t1]
SET field1 = t2.field1,
field2 = CASE WHEN <field 2 changed> THEN t2.field2 ELSE t1.field2 END,
field3 = CASE WHEN t1.field3 <> t2.field3 THEN t2.field3 else t1.field3 END
FROM <table1> as t1
LEFT JOIN <table2> as t2 on t1.key1 = t2.key1
Upvotes: 2