描述
该语句用来根据一张源表更新一张目标表的数据,可以对目标表进行插入、更新或者删除。
语法
MERGE [hint_options] INTO target_table_name [opt_alias]
USING source_table_name [opt_alias]
ON (expr)
[merge_update_clause] [merge_insert_clause]
merge_update_clause:
WHEN MATCHED THEN UPDATE SET update_asgn_list [WHERE expr] [DELETE WHERE expr]
merge_insert_clause:
WHEN NOT MATCHED THEN INSERT opt_insert_columns VALUES '(' insert_vals ')' [WHERE expr]
1、新建表
create table t1 (col1 int, col2 int);
create table t2 (col1 int, col2 int);
insert into t1 values(0,0);
insert into t1 values(1,null);
insert into t1 values(2,null);
insert into t2 values(1,1);
insert into t2 values(2,20);
insert into t2 values(3,3);
insert into t2 values(4,40);
SYS@ora11g> SET NULL "NULL";
SYS@ora11g> select * from t1;
COL1 COL2
---------- ----------
0 0
1 NULL
2 NULL
SYS@ora11g> select * from t2;
COL1 COL2
---------- ----------
1 1
2 20
3 3
4 40
2、需求
如果 t1.col1 在 t2 中能够找到 t1.col1 取值相同的行,如果 t1.col2 取值为空,那么使用 t2.col2 更新 t1.col2;如果更新之后 t1.col2 >= 10,那么删除该行。
如果 t2.col1 在 t1 中找不到取值相同的行,将 t2 中的这行插入到 t1 中,且只插入满足 t2.col2 < 10 的行。
merge into t1 using t2 on (t1.col1 = t2.col1)
when matched then update set t1.col2 = t2.col2 where t1.col2 is null delete
where t1.col2 >=10
when not matched then insert values (t2.col1,t2.col2)
where t2.col2 <10 ;
--执行
merge into t1 using t2 on (t1.col1 = t2.col1)
when matched then update set t1.col2 = t2.col2 where t1.col2 is null delete
where t1.col2 >=10
when not matched then insert values (t2.col1,t2.col2)
2 3 4 5 where t2.col2 <10 ;
3 rows merged.
SYS@ora11g> commit;
Commit complete.
--确认是否符合需求
SYS@ora11g> select * from t1;
COL1 COL2
---------- ----------
0 0
1 1
3 3
SYS@ora11g> select * from t2;
COL1 COL2
---------- ----------
1 1
2 20
3 3
4 40
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




