使用Merge Into可以让你实现如下功能:
在插入数据时,如果目标数据表中,该数据已经存在(当然是指某些字段值相同),则执行更新操作,否则执行插入操作。
Merge Into的这个强大功能,常常用于两个数据表之间的数据同步。
使用示例:
table_1(id,c1,c2,c3,c4);
table_2(id,c1,c2,c3,c4);
Merge Into table_2 t2
using (select id,c1,c2,c3,c4 from table_1) t1
on (t2.c1 = t1.c1 and t2.c2 = t1.c2)
when matched then
update set t2.c3 = t1.c3
when not matched then
insert (t2.id,t2.c1,t2.c2,t2.c3,t2.c4)
values (t1.id,t1.c1,t1.c2,t1.c3,t1.c4)
注意,这里不能更新on条件中使用到的字段。
另外,可以使用常量过滤器on(0=1),来实现无条件插入所有源数据。
补充:
--update部分可以包含一个delete子句(有自己的where子句),用来删除符合on条件并且被update后的、并且符合delete自带where子句的过滤条件的行。
Merge Into table_2 t2
using (select id,c1,c2,c3,c4 from table_1) t1
on (t2.c1 = t1.c1 and t2.c2 = t1.c2)
when matched then
update set t2.c3 = t1.c3
delete where (t2.c4 is null)
when not matched then
insert (t2.id,t2.c1,t2.c2,t2.c3,t2.c4)
values (t1.id,t1.c1,t1.c2,t1.c3,t1.c4)
阅读(1285) | 评论(0) | 转发(0) |