2015-12-21 71 views
0

我需要在oracle中执行以下操作,但这不兼容。基本上基于目标和来源。只有使用SQL任何一个可以提出任何替代方案:基于目标和源的Oracle合并

merge into x as target using y as Source on target.ID = Source.ID 
when not matched by target then insert 
when matched then update 
when not matched by source and target.ID is not null then 
update whatevercolumn = 'isdeleted' 
+0

什么是“不兼容”?你从哪里来? – hol

+0

“合并”语句(包括示例)的完整语法记录在手册中:https://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_9016.htm#SQLRF01606 –

回答

0

一个典型的MERGE语句格式是沿着线的东西:

merge into target_table tgt 
using source_dataset src 
    on (<join conditions>) 
when matched then 
    update set tgt.col1 = src.col1, 
      tgt.col2 = src.col2, 
      ... 
    where <predicates, if required> 
when not matched then 
    insert (tgt.col1, tgt.col2, ...) 
    values (src.col1, src.col2, ...); 

你必须修改你的逻辑这个格式,如果你想要合并工作。

如果您无法做到这一点,请使用目标表和源表的样本数据以及您期望的结果,以及您尝试执行的更新背后的逻辑来更新您的问题。


如果你需要更新你的目标表中不会出现在您的源数据,以及不出现的记录的记录,那么你就需要写一个子查询,做一个完整的外部之间的连接这两个表格,然后将其用作您的源数据集。

喜欢的东西:

merge into target_table trg 
using (select coalesce(srce.target_join_col, targ.source_join_col) join_col, 
       coalesce(srce.other_col1, targ.other_col1) other_col1, 
       coalesce(srce.other_col2, targ.other_col2) other_col2, 
       ... 
     from target_table targ 
       full outer join source_table srce on (targ.target_join_col = srce.source_join_col)) src 
    on (trg.target_join_col) 
when matched then 
    update set trg.other_col1 = src.other_col1, 
      trg.other_col2 = src.other_col2, 
      ... 
    where  trg.other_col1 != src.other_col1 
    or   trg.other_col2 != src.other_col2 
    ... 
when not matched then 
    insert (trg.target_join_col, trg.other_col1, trg.other_col2, ...) 
    values (src.source_join_col, src.other_col1, src.other_col2, ...); 

注:未经测试,因为您没有提供任何测试用例或数据供我们使用。

+0

条件1:我想要如果记录存在于源表中而不存在于目标表中,则插入新记录Condition2:另外,如果记录存在于目标中但不存在于源中,我还想更新记录吗? – user2519971

+0

Oracle仅支持使用源表中的记录更新目标表。您必须有单独的查询才能更新目标表中不在源表中的记录。或者,您可以编写一个查询,在两个表上执行完整的外部联接并将其用作源查询 – Boneist

+0

@ user2519971我已更新我的答案,以包含如何编写合并以支持这两种条件的示例你提到。 – Boneist