如何在oracle中更新多个值?

How to update multiple values in oracle?

我有两个 table:

table 1:
|Project type|Quarter1|Quarter2|Quarter3|Quarter4|
|------------|--------|--------|--------|--------|
|type1       |1       |3       |5       |7       |
|type2       |2       |4       |6       |8       |

table 2:
|Project|Value|Quarter|
|-------|-----|-------|
|type1  |     |1      |
|type2  |     |1      |
|type1  |     |2      |
|type2  |     |2      |
|type1  |     |3      |
|type2  |     |3      |
|type1  |     |4      |
|type2  |     |4      |

我想用 table 1 中的数据更新 table 2 值部分,预期结果是:

|Project|Value|Quarter|
|-------|-----|-------|
|type1  |1    |1      |
|type2  |2    |1      |
|type1  |3    |2      |
|type2  |4    |2      |
|type1  |5    |3      |
|type2  |6    |3      |
|type1  |7    |4      |
|type2  |8    |4      |

我知道更新单个值可以写成:

update table2 a 
   set a.value = (select Quarter1 
                    from table1
                   where projecttype = 'type1')
 where a.project = 'type1'
   and a.quarter = '1';

请告诉我如何一次性更新所有值?

谢谢!

一种方法是使用 merge 语句:

merge into table_2 t
  using    table_1 s
     on    (t.project = s.project_type)
when matched then update
  set t.value = case t.quarter when 1 then s.quarter1
                               when 2 then s.quarter2
                               when 3 then s.quarter3
                               when 4 then s.quarter4 end
;

这是我对使用循环重复更新过程的主要想法。正文参考mathguy的回答(再次感谢)。在这种情况下,它可能会使代码复杂化,但当 table1 中有许多列时会很有用,例如年份而不是季度。

declare
  
  quart_num number;
  code      varchar2(2000);
begin

  for quart_num in 1..4
  loop
      code := 'merge into table2 a
               using table1 b
               on (a.project = b.projecttype)
               when matched then
               update set a.value = quarter'||
               quart_num || 'where a.quarter =' ||quart_num;
      execute immediate(code);
   end loop;
end;