merge主要是在insert数据时,数据库再进行一次判断数据是否重复的筛选工作,主要语法为:
merge into ……
using……
on......
when matched then……
when not matched then ……
--先建2个表
create table TEST111
(
ID VARCHAR2(20),
NAME VARCHAR2(30),
AGE INTEGER
)
;
create table TEST222
(
ID VARCHAR2(20),
NAME VARCHAR2(30),
AGE INTEGER
)
;
insert into TEST111 (ID, NAME, AGE)
values ('100001', 'MADENGMEI', 20);
insert into TEST111 (ID, NAME, AGE)
values ('100002', 'WANGYIYANG', 30);
insert into TEST111 (ID, NAME, AGE)
values ('100003', 'HUASHENGMI', 40);
insert into TEST111 (ID, NAME, AGE)
values ('100004', 'DADOUYOU', 50);
commit;
insert into TEST222 (ID, NAME, AGE)
values ('100003', 'huashengmi', 21);
insert into TEST222 (ID, NAME, AGE)
values ('100004', 'kaixinguo', 30);
insert into TEST222 (ID, NAME, AGE)
values ('100005', 'meitesi', 50);
insert into TEST222 (ID, NAME, AGE)
values ('100006', 'yichun', 55);
commit;
merge into test111 a
using test222 b --要查询的表(也可以是一条查询语句)
on (a.id = b.id) --条件(记得加括号)
when matched then
update set a.name = b.name,a.age = b.age
delete where b.age<25
when not matched then
insert values(b.id,b.name,b.age);
其实TD里面也有这用法,就是有一点点小区别:
merge into pims_ptemp.test111 a
using pims_ptemp.test222 b
on (a.id = b.id)
when matched then
update set name = b.name,age = b.age --a表的字段不用带别名,且TD不支持update和delete一起操作
when not matched then
insert values(b.id,b.name,b.age); --这里的values可要可不要
update那一段也不知道为什么不让加test111表的别名,很怪异,我弄了很长时间也找不到错误,也是请教了别人才知道的,TD不支持判断插入的同时做删除操作。