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 ! ]
应用:
在创建另两个表fzq1和fzq2
--全部男生记录
create table fzq1 as select * from fzq where sex=1;
--全部女生记录
create table fzq2 as select * from fzq where sex=0;
merge into fzq1 aa --fzq1表是需要更新的表
using fzq bb -- 关联表
on (aa.id=bb.id) --关联条件
when matched then --匹配关联条件,作更新处理
update set
aa.chengji=bb.chengji+1,
aa.name=bb.name --此处只是说明可以同时更新多个字段。
when not matched then --不匹配关联条件,作插入处理。如果只是作更新,下面的语句可以省略。
insert values( bb.id, bb.name, bb.sex,bb.kecheng,bb.chengji);
--可以自行查询fzq1表。
涉及到多个表关联的例子,我们以三个表为例,只是作更新处理,不做插入处理。当然也可以只做插入处理
--将fzq1表中女生记录的成绩+1,没有直接去sex字段。而是fzq和fzq2关联。
merge into fzq1 aa --fzq1表是需要更新的表
using (select fzq.id,fzq.chengji
from fzq join fzq2
on fzq.id=fzq2.id) bb -- 数据集
on (aa.id=bb.id) --关联条件
when matched then --匹配关联条件,作更新处理
update set
aa.chengji=bb.chengji+1
--可以自行查询fzq1表。
不能做的事情
merge into fzq1 aa
using fzq bb
on (aa.id=bb.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 fzq1
set id=(select id+1 from fzq where fzq.id=fzq1.id)
where id in
(select id from fzq)
--使用update就可以更新,如果有更好的方法,谢谢反馈!