merge into基本用法

来源:这里教程网 时间:2026-03-03 12:05:04 作者:

由于merge into平时很少用,但这次用到它来给记录做插入更新,于是简单记下最基本的用法。这里的例子就是给一个表中符合条件的数据做个值计数的更新,如果找到符合ID条件的记录,那么就将其值字段加1,否则就插入这条新的记录,并初始化值。 创建测试表并插入数据: create table test1(id number, val number); insert into test1 values(101, 1); insert into test1 values(102, 1); commit; select * from test1;         ID        VAL ---------- ----------        101          1        102          1 做merge into操作,新的一条数据被插入: merge into test1 t1 using (select count(*) cnt from test1 where id = 103) t2 on (cnt <> 0) when matched then   update set val = val + 1 where id = 103 when not matched then   insert values(103, 1); commit; select * from test1;         ID        VAL ---------- ----------        101          1        102          1        103          1 再执行一个merge into后,数据被更新:         ID        VAL ---------- ----------        101          1        102          1        103          2

相关推荐