Merger into是oracle从9i开始增加的一个语句,从merge的字面上的意思:合并,兼并不难理解merge在oracle中的含义,merge在oracle所起的作用是:如果你从以组值中有选择的更新和插入到到一张表,具体来说是:如果该表中已经匹配了这组值的某些条件,那么可以使用这组值的部分数据来更新这个表的,如果该表中无法匹配了这组值的某些条件,那么可以使用这组值的数据来为这个表新增一条数据。
无论你在使用任何DBMS,你总是难以避免的将会遇到上面提到的这种需求,如果你不使用merge语句,你将会不得不在程序中增加大段的代码,或者是在oracle用很长的代码来实现。好在现在我们有了merge,可以帮我们省下很多时间。
好了废话少说:
Merge 的基本语法是这样的
Merge into table[alias]
Using table or sql query [alias]
On condition
When matched then
Update set ….
When not matched then
Insert values…
以上是merge的基本语法,其中alias是为表或者查询写的别名
如果你看着空洞的语法觉得头很痛,看下面的例子吧
首先我们创建两个表
create table test1(id int,name varchar(20));
create table test2(id int,name varchar(20))
然后随意插入几行数据
insert into test1 values(1,’hi’);
insert into test1 values(2,’hello’);
insert into test2 values(2,’你好’);
insert into test2 values(3,’morning’);
下面我们要使用了merge了,将test2中的数据有选择地转移或者更新到test1中
如果你运行了下下面的merge语句,你将会的到一个错误,这是因为oracle规定在merge语句中不能更新作为连接的列,也就是on后面的那些列
merge into test1 t1
using test2 t2
on (t1.id = t2.id)
when matched then
update set t1.id = t2.id
when not matched then
insert values(t2.id,t2.name);
所以将会得到如下的错误,虽然这个错误翻译的并不怎么样,甚至带有明显的误导
on (t1.id = t2.id)
*
ERROR 位于第 3 行:
ORA-00904: “T1″.”ID”: 无效的标识符
好了,知错就改,我们再来运行下面的merge语句。
merge into test1 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)
成功执行了,我们来验证一下。
select * from test1;