简体   繁体   中英

Updating multiple columns using Case

I have a query that looks like below:

UPDATE some_table
SET column_x = CASE WHEN x_specific_condition THEN new_value_for_x ELSE column_x END,
    column_y = CASE WHEN y_specific_condition THEN new_value_for_y ELSE column_y END, 
WHERE some_more_conditions

Problem with above is, each column (x, y) still gets updated with their own value if some_more_conditions return true irrespective of their specific conditions returning true. I tried removing ELSE from above, but no luck

I am combining as some_more_conditions are same for both cases, I think its better to perform all in 1 update (suggestions welcome)

Do you know if there is a way that I can perform the above update in 1 query by skipping the individual columns where the specific conditions do not match (basically avoid overwriting of same values)

To do this in one update, you would need to expand the where clause:

UPDATE some_table
    SET column_x = CASE WHEN x_specific_condition THEN new_value_for_x ELSE column_x END,
        column_y = CASE WHEN y_specific_condition THEN new_value_for_y ELSE column_y END, 
    WHERE some_more_conditions AND
          (x_specific_condition OR
           y_specific_condition
          );

An alternative is to use multiple updates, but that could be more expensive:

UPDATE some_table
    SET column_x = new_value_for_x
    WHERE some_more_conditions AND x_specific_condition;

UPDATE some_table
    SET column_y = new_value_for_y
    WHERE some_more_conditions AND y_specific_condition;

update [table_name] set [column_name_1] = case when [column_name_1] = [condition_1] then [condition_2] else [column_name_1] end, [column_name_2] = case when [column_name_2] = [condition_1] then [condition_2] else [column_name_2] end, where condition;

Note: [table_name] is your table name, [column_name] is your column name in which you want to update values. you can update values without where condition as well.

find screenshot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM