带有条件更新的oracle upsert

时间:2013-10-25 14:57:48

标签: sql oracle merge upsert

我想根据以下编码在DB中插入一行

if table t has doesnot not have row with key X:
      insert into t mystuff..
else
    if  update t set mystuff... where mykey=X if existingversion < NewVersion

我知道正常合并可以按如下方式使用

MERGE INTO (SELECT * FROM mytable WHERE status='active') old
     USING (SELECT * FROM newtable) new
        ON (new.id = old.id)
      WHEN MATCHED THEN UPDATE SET old.data1=new.data1;

但是我如何处理合并的条件更新?

1 个答案:

答案 0 :(得分:0)

您可以过滤要插入的行,例如:

MERGE INTO (SELECT * FROM mytable WHERE status='active') old
     USING (SELECT * 
              FROM newtable n
             WHERE NOT EXISTS (SELECT NULL 
                                 FROM mytable m
                                WHERE m.id = n.id
                                  AND m.version >= n.version) new
        ON (new.id = old.id)
      WHEN MATCHED THEN UPDATE SET old.data1=new.data1;