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]
create table A_MERGE
(
id NUMBER not null,
name VARCHAR2(12) not null,
year NUMBER
);
create table B_MERGE
(
id NUMBER not null,
aid NUMBER not null,
name VARCHAR2(12) not null,
year NUMBER,
city VARCHAR2(12)
);
create table C_MERGE
(
id NUMBER not null,
name VARCHAR2(12) not null,
city VARCHAR2(12) not null
);
commit;
其表结构截图如下图所示:
A_MERGE表结构:
B_MERGE表结构
C_MERGE表结构
1.正常模式
先向A_MERGE和B_MERGE插入测试数据:
insert into A_MERGE values(1,'liuwei',20);
insert into A_MERGE values(2,'zhangbin',21);
insert into A_MERGE values(3,'fuguo',20);
commit;
insert into B_MERGE values(1,2,'zhangbin',30,'吉林');
insert into B_MERGE values(2,4,'yihe',33,'黑龙江');
insert into B_MERGE values(3,3,'fuguo',,'山东');
commit;
此时A_MERGE和B_MERGE表中数据截图如下:
A_MERGE表数据:
B_MERGE表数据:
然后再使用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;
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;
update B_MERGE set name='yihe++' where id=2;
update B_MERGE set name='liuwei++' where id=4;
insert into B_MERGE values(6,6,'ningqin',23,'江西');
insert into B_MERGE values(7,7,'bing',24,'吉安');
commit;
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;
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表在merge之前的数据截图如下:
B_MERGE数据截图如下:
C_MERGE表在merge之后数据截图如下:
6.带delete的update
MERGE提供了在执行数据操作时清除行的选项. 你能够在WHEN MATCHED THEN UPDATE子句中包含DELETE子句.
DELETE子句必须有一个WHERE条件来删除匹配某些条件的行.匹配DELETE WHERE条件但不匹配ON条件的行不会被从表中删除.