使用不同的where子句更新多个列

时间:2018-07-25 12:09:22

标签: sql oracle sql-update

所以我有以下两个更新语句:

UPDATE table1 SET column1_new = "1" WHERE column1_old IS NOT NULL
UPDATE table1 SET column2_new = "2" WHERE column2_old IS NOT NULL

有没有办法在一个数据库调用中做到这一点?

2 个答案:

答案 0 :(得分:2)

在这种情况下,您可能会发现nvl2函数很有用,但是您无法避免在where条件下使用or

update table1 set column1_new = nvl2(column1_old, 1, column1_new),
                  column2_new = nvl2(column2_old, 2, column2_new)
where column1_old is not null or column2_old is not null;

答案 1 :(得分:1)

您可以这样做:

UPDATE table1
    SET column1_new = (CASE WHEN column1_old IS NOT NULL THEN 1 ELSE column1_new),
        column2_new = (CASE WHEN column2_old IS NOT NULL THEN 2 ELSE column2_new)
    WHERE column1_old IS NOT NULL OR column2_old IS NOT NULL;

但是,我认为使用update查询更为简单。