merge语句
可以指定对2个表执行合并操作
语法
merge into tableName1
using tableName2 on joinCondition
when matched then update set ….
when not matched then insert …..value ……
tableName1:需要合并的目标表
tableName2:需要合并的源表
joinCondition:合并条件
when matched then update set ….:如果符合合并条件,执行更新操作
when not matched then insert …..value …… 不符合合并条件,执行插入操作
update字句:将源表中符合条件的数据合并到目标表中
insert字句:将源表中不符合条件的数据合并到目标表中
提供测试的数据
create table student2(
sno varchar2(10) primary key,
sname varchar2(20),
sage number(2),
cno varchar2(2)
);
insert into student2 values(‘2’,’lili’,18,’1’);
insert into student2 values(‘3’,’lili’,18,’1’);
insert into student2 values(‘4’,’lili’,20,’1’);
insert into student2 values(‘5’,’lili’,21,’1’);
create table student3(
sno varchar2(10) primary key,
sname varchar2(20),
sage number(2),
cno varchar2(2)
);
insert into student3 values(‘2’,’lilix’,18,’1’);
insert into student3 values(‘6’,’lilia’,18,’1’);
insert into student3 values(‘7’,’lilib’,20,’1’);
insert into student3 values(‘8’,’lilic’,21,’1’);
commit;
操作
merge into student2 s2
using student3 s3
on (s2.sno=s3.sno)
when matched then
update set s2.sname=s3.sname
when not matched then
insert (s2.sno,s2.sname,s2.sage,s2.cno) values (s3.sno,s3.sname,s3.sage,s3.cno)
说明:
合并条件 s2.sno=s3.sno
满足合并条件:修改s2表的sname值
不满足合并添加:添加s3表的数据到收表中.
查询结果
源表的数据没变化,目标表的数据已经改变