12

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)

2 Answers 2

25
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)
Sign up to request clarification or add additional context in comments.

1 Comment

I think you need to include the ELSE display_order with the first CASE block, and ELSE title in the second CASE block. Otherwise, title will be NULL in first case, and display_order will be NULL in the second case.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.