【问题标题】:Update or Insert based on the value of a column in the table [duplicate]根据表中列的值更新或插入[重复]
【发布时间】:2012-07-03 03:40:55
【问题描述】:

可能重复:
Oracle: how to UPSERT (update or insert into a table?)

你们能否给我一个关于如何在以下情况下进行的建议:

Read table 2 column 1 
if value says the record exists in table 1
update table 1 record with table 2 record details
else(value says the record does not exist in table 1)
insert table 1 record with table 2 record details

我是 Oracle SQL 的初学者,如果有更好的方法,请告诉我..我正在考虑使用游标来解决这个问题..

【问题讨论】:

  • 你能再解释一下吗?为什么不能对照表 1 检查?

标签: sql oracle


【解决方案1】:

【讨论】:

    【解决方案2】:

    最简单的答案是使用merge 语句:

    MERGE INTO table1 a
    USING ( select column1, column2 
              from table2 ) b
    ON ( a.column1 = b.column1 )
    WHEN MATCHED THEN 
      update set a.column2 = b.column2
    WHEN NOT MATCHED THEN 
      insert (a.column1, a.column2)
      values (b.column1, b.column2)
    

    简单地说,这需要从selecttable2 的所有内容。然后在条件下将此查询连接到table1。如果有“匹配”,则更新,否则插入。

    documentation has more information 关于您目前不需要的各种附加选项。

    【讨论】:

    • 谢谢本,它几乎达到了目的..第一次成功运行但如果我再次运行它会抛出错误unable to get a stable set of rows in the source tables任何解决这个问题..尝试使用 Distinct 中提到的其他线程之一,但它不起作用。
    • 当心 - oracle9 中有许多与此功能有关的错误。在升级到 oracle10 之前,我们甚至被禁止使用它。
    • @javanoob,听起来你在第一次运行它之后没有一组唯一的行,即你在表上没有唯一的约束/索引。您在运行一次之后加入的列是唯一的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2020-07-28
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    相关资源
    最近更新 更多