1 merge into的形式
merge into [ target - table ] a using [ source - table sql ] b on ([ conditional expression ] and [ .. . ] .. .) when matched then [ update sql ] when not matched then [ insert sql ]
作用:判断b表和a表是否满足on中的条件,如果满足则用b表中的数据去更新a表,如果不满足,则将b表中的数据插入到a表。
2 测试表数据
a表: a_merge
b表: b_merge
(1)使用merge into用b_merge表中的数据来更新a_merge表中的数据
merge into a_merge a using (select b.aid, b.name, b.year from b_merge b) c on (a.id = c.aid) when matched then update set a.year = c.year when not matched then insert (a.id, a.name, a.year) values (c.aid, c.name, c.year); commit;
执行上述语句之后a_merge表的数据如下:
解析:ID为4的信息为insert的,ID为2和3的数据的year字段被b表的year字段update。
(2)使用b_merge来更新a_merge,但是仅有update语句,没有写insert语句。
a表: a_merge
b表: b_merge
merge into a_merge a using (select b.aid, b.name, b.year from b_merge b) c on (a.id = c.aid) when matched then update set a.year = c.year; commit;
执行上述语句之后a_merge表的数据如下:可以发现仅仅更新了AID=1的year字段,没有插入AID=4的数据。
(3)使用b_merge来更新a_merge,但是仅有insert语句,没有写update语句。
a表: a_merge
b表: b_merge
merge into a_merge a using (select b.aid, b.name, b.year from b_merge b) c on (a.id = c.aid) when not matched then insert (a.id, a.name, a.year) values (c.aid, c.name, c.year); commit;
执行上述语句之后a_merge表的数据如下:
(4)带where条件的insert和update,使用b_merge表来更新a_merge表,但是分别在insert和update后面添加了条件限制。控制数据的更新和插入。
我们在on中进行完条件匹配之后,还可以在后面的insert和update语句中对on筛选出来的记录再做一次条件判断,用来控制哪些需要更新,哪些需要插入。
a表: a_merge
b表: b_merge
merge into a_merge a using (select b.aid, b.name, b.year, b.city from b_merge b) c on (a.id = c.aid) when matched then update set a.name = c.name where c.city != '江西' when not matched then insert (a.id, a.name, a.year) values (c.aid, c.name, c.year) where c.city = '江西'; commit;
执行上述语句之后a_merge表的数据如下:
(5)无条件的insert
有时我们需要将一张表中所有数据插入到另外一张表中,此时就可以添加常量过滤谓词来实现,让其只满足匹配或不匹配,这样就只有update或者只有insert,这里我们要无条件全插入,则只需要将on中条件设置为永假。
c表: c_merge
b表: b_merge
merge into c_merge c using (select b.aid, b.name, b.city from b_merge b) c on (1 = 0) when not matched then insert (c.id, c.name, c.city) values (b.aid, b.name, b.city); commit;
执行上述语句之后c_merge表的数据如下:
参考博文:https://blog.csdn.net/jeryjeryjery/article/details/70047022
标签:insert,name,into,update,merge,year,oracle,aid From: https://www.cnblogs.com/daytoy105/p/16655721.html