从ORACLE 9i开始,ORACLE提供了可以同时执行 insert ,update的命令merge 。
创建测试表 info
SQL> create table info(name varchar2(10),age number, address varchar2(10));
Table created.
插入3条测试数据
insert into info values('robinson',100,'chongqing');
insert into info values('luobingsen',100,'chongqing');
insert into info values('luoluo',100,'chongqing');
创建测试表 information
SQL>
create table information(name varchar2(10),id number,age number,address varchar2(10),school varchar2(10));
Table created.
插入4条测试数据
insert into information values('robinson',1,21,'chongqing','xinandaxue');
insert into information values('luobingsen',2,22,'beijing','xinandaxue');
insert into information values('luoluo',3,23,'shanghai','xinandaxue');
insert into information values('lbs',4,24,'tianjin','xinandaxue');
此时info 表中数据如下
SQL> select * from info;
NAME AGE ADDRESS
---------- ---------- ----------
robinson 100 chongqing
luobingsen 100 chongqing
luoluo 100 chongqing
information 表中数据如下
SQL> select * from informATION;
NAME ID AGE ADDRESS SCHOOL
---------- ---------- ---------- ---------- ----------
robinson 1 21 chongqing xinandaxue
luobingsen 2 22 beijing xinandaxue
luoluo 3 23 shanghai xinandaxue
lbs 4 24 tianjin xinandaxue
现在,我想把information表name,age,address的信息插入到 info表中,
如果info 表中没有 information的信息,那么直接将该信息添加到info表
如果info 表中有information的信息,那么以information的信息为准,更新info表
SQL> merge into info i
2 using (select name,age,address from information) j
3 on (i.name=j.name)
4 when matched then update set i.age=j.age,i.address=j.address
5 when not matched then insert values(j.name,j.age,j.address);
4 rows merged.
SQL> select * from info;
NAME AGE ADDRESS
---------- ---------- ----------
robinson 21 chongqing
luobingsen 22 beijing
luoluo 23 shanghai
lbs 24 tianjin