Merge into 简介

Merge into 简介
MERGE语句是Oracle9i新增的语法,用来合并UPDATE和INSERT语句。

语法:

MERGE INTO [your table-name] [rename your table here]

USING ( [write your query here] )[rename your query-sql and using just like a table]

ON ([conditional expression here] AND [...]...)

WHEN MATHED THEN [here you can execute some update sql or something else ]

WHEN NOT MATHED THEN [execute something else here ! ]

实例1:

merge into table_1 a
using table_2 b
on (a.id=b.id)
when matched then
update set
a.chengji=b.chengji,
a.name=b.name                   --此处只是说明可以同时更新多个字段。
when not matched then                  --不匹配关联条件,作插入处理。如果只是作更新,下面的语句可以省略。
insert values( b.id,b.name,b.sex,b.kecheng,b.chengji);

实例2:
/*涉及到多个表关联的例子,我们以三个表为例,只是作更新处理,不做插入处理。当然也可以只做插入处理*/

merge into table_1 a
using (select table_2.id,table_2.chengji
from table_2 join table_3
on table_2.id=table_3.id) b               -- 数据集
on (a.id=b.id)                      --关联条件
when matched then                   --匹配关联条件,作更新处理
update set
a.chengji=b.chengji

/*不能做的事情*/
merge into table_1 a
using table_1 b
on (a.id=b.id)
when matched then
update set
aa.id=bb.id+1
/*系统提示:
ORA-38104: Columns referenced in the ON Clause cannot be updated: "AA"."ID"
我们不能更新on (aa.id=bb.id)关联条件中的字段*/
想要修改关联条件的字段可直接使用update。

posted @ 2019-11-13 15:51  AWNUygah  阅读(179)  评论(0编辑  收藏  举报