【问题标题】:Update through merge通过合并更新
【发布时间】:2014-07-01 17:58:59
【问题描述】:

我在创建过程时遇到了设计问题。

假设我必须使用同一行中其他列中的数据更新表中的所有行。假设table1 有3 列ABC,我需要将所有行更新为C=A+B。所以我可以使用:

update table1 set C=A+B;

但我需要使用以下方法来执行此操作:

merge tab1e1 using (some query) on (some condition)
when matched update
 C=A+B
when not matched 
null;

有没有办法通过操纵“一些查询”和“一些条件”来做到这一点?

【问题讨论】:

  • 为什么会有问题?您可以在 when matched 子句中执行 update set c=a+b。使其成为合并将限制您更新哪些行 - 只有您知道 some querysome condition 需要是什么,以及为什么需要使用合并?我不明白你的实际问题是什么,或者你坚持什么。一个具体的例子可能会有所帮助,这是相当模糊的。
  • 或者你的意思是你还想更新表中的每一行;但是你想通过合并来做到这一点吗?这样when matched 总是正确的?如果是这样……为什么?
  • 感谢您的快速响应.. 实际上我需要通过合并来完成。这是在运行时创建的查询的超级简化版本。这是合并语句将使用其自身的列更新表的所有行的场景
  • 道歉..这是一个愚蠢的问题..我不知道为什么我整天都在为此苦苦挣扎:)我通过使用'select 1 from dual'来获得解决方案(一些查询)和'1=1' 用于(某些条件)

标签: sql oracle sql-update sql-merge


【解决方案1】:

我真的不明白你为什么要使用合并而不是更新,但如果你真的需要,你可以使用 dual 来创建你的 using 子句和 on 条件总是正确的:

merge into table1
using (select null from dual)
on (1 = 1)
when matched then update set c = a + b;

一些样本数据:

create table table1 (a number, b number, c number);
insert into table1 values (1, 2, null);
insert into table1 values (3, 4, null);
insert into table1 values (5, 6, null);

merge into table1
using (select null from dual)
on (1 = 1)
when matched then update set c = a + b;

3 rows merged.

select * from table1;

         A          B          C
---------- ---------- ----------
         1          2          3 
         3          4          7 
         5          6         11 

SQL Fiddle.

【讨论】:

  • 感谢 Alex 抽出宝贵时间 .. 这是一个设计限制。这就是为什么我需要以“合并方式”进行此更新
猜你喜欢
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-11
  • 1970-01-01
  • 2016-12-24
相关资源
最近更新 更多