功能描述
通过MERGE INTO语句,将目标表和源表中数据针对关联条件进行匹配,若关联条件匹配时对目标表进行UPDATE,无法匹配时对目标表执行INSERT。
此语法可以很方便地用来合并执行UPDATE和INSERT,避免多次执行。
进行MERGE INTO操作的用户需要同时拥有目标表的UPDATE和INSERT权限,以及源表的SELECT权限。
示例:
sql
--测试表1
DROP TABLE test;
create table test
(
id int NOT NULL,
name varchar2(50) DEFAULT NULL ,
CONSTRAINT "pk_id2" PRIMARY KEY (id)
) ;
insert into test
select '1','one' FROM dual
union all
select '2','two' FROM dual
union all
select '3','three' FROM dual
SELECT * FROM test;
ID NAME
1 one
2 two
3 three
--测试表2
drop TABLE test2;
create table test2
(
id int NOT NULL,
name varchar2(50) DEFAULT NULL ,
CONSTRAINT "pk_id" PRIMARY KEY (id)
) ;
insert into test2
select '1','oneone' FROM dual
union all
select '4','four' FROM dual
SELECT * FROM test2;
1 oneone
4 four
--merge into 语法
merge into test t1
using test2 t2
on (t1.id = t2.id)
WHEN MATCHED THEN
update set t1.name = t2.name
WHEN NOT MATCHED THEN
insert values (t2.id, t2.name);
Updated ROWS 2
SELECT * FROM test;
ID NAME
1 oneone
2 two
3 three
4 four