首页 > 应用开发 > IT综合 > merge用法测试随手记!
matched之后的delete语法是10g之后才有的,使用起来更加灵活方便了;而且10g中还增加了where子句可以控制条件
[@more@]测试1:
SQL> create table t(id int , name varchar2(10));
表已创建。
SQL> insert into t(id) values(1);
已创建 1 行。
SQL> insert into t(id) values(2);
已创建 1 行。
SQL> insert into t(id) values(3);
已创建 1 行。
SQL> insert into t values(8,'h');
已创建 1 行。
SQL> insert into t values(null,'m');
已创建 1 行。
SQL> commit;
提交完成。
SQL> create table tt(id int , name varchar2(10));
表已创建。
SQL> insert into tt values(1,'a');
已创建 1 行。
SQL> insert into tt values(2,'b');
已创建 1 行。
SQL> insert into tt values(3,'c');
已创建 1 行。
SQL> insert into tt values(4,'d');
已创建 1 行。
SQL> insert into tt values(5,'e');
已创建 1 行。
SQL> insert into tt values(null,'f');
已创建 1 行。
SQL> commit;
提交完成。
SQL> select * from t;
ID NAME
---------- ----------
1
2
3
8 h
m
SQL> select * from tt;
ID NAME
---------- ----------
1 a
2 b
3 c
4 d
5 e
f
已选择6行。
SQL> insert into tt values(null , 'm');
已创建 1 行。
SQL> commit;
提交完成。
SQL> edit
已写入 file afiedt.buf
1 merge into t
2 using tt on (t.id=tt.id)
3 when matched then update set name=tt.name
4* when not matched then insert(id , name) values(tt.id , tt.name)
SQL> /
7 行已合并。
--注意id=null合并之后的结果
SQL> select * from tt;
ID NAME
---------- ----------
1 a
2 b
3 c
4 d
5 e
f
m
已选择7行。
SQL> select * from t;
ID NAME
---------- ----------
1 a
2 b
3 c
8 h
m
m
f
5 e
4 d
已选择9行。
SQL> rollback;
回退已完成。
SQL>
--=================================
测试2:
SQL> create table tt1(id int , name varchar2(10) , age int);
表已创建。
SQL> create table tt2(id int , name varchar2(10));
表已创建。
SQL> insert into tt2 select id , name from tt1 where id<4;
已创建3行。
SQL> commit;
提交完成。
SQL> select * from tt1;
ID NAME AGE
---------- ---------- ----------
1 a 10
2 b 20
3 c 30
4 d 40
5 e 50
SQL> select * from tt2;
ID NAME
---------- ----------
1 a
2 b
3 c
SQL> update tt1 set name=null;
已更新5行。
SQL> commit;
提交完成。
--这里注意修改的始终是tt1表,条件delete where (age>20)删除了tt1中id=3的记录
SQL> merge into tt1
2 using (select *from tt2) tt2 --纯粹是为了验证子查询才这样写的,没有别的意义
3 on (tt1.id=tt2.id)
4 when matched then update set name=tt2.name
5 delete where (age>20)
6 when not matched then insert(id,age) values(tt2.id,100);
3 行已合并。
SQL> select * from tt1;
ID NAME AGE
---------- ---------- ----------
1 a 10
2 b 20
4 40
5 50
SQL> rollback;
回退已完成。
SQL> select * from tt2;
ID NAME
---------- ----------
1 a
2 b
3 c
SQL> insert into tt2 values(6 , 'm');
已创建 1 行。
SQL> insert into tt2 values(7 , 'n');
已创建 1 行。
SQL> commit;
提交完成。
SQL>
SQL> edit
已写入 file afiedt.buf
1 merge into tt1
2 using (select *from tt2) tt2
3 on (tt1.id=tt2.id)
4 when matched then update set name=tt2.name
5 delete where (age>20)
6 when not matched then insert(id,age) values(tt2.id,100)
7* where (tt2.id=6)
SQL> /
3 行已合并。
--注意tt2中id=6的数据被插入了
SQL> select * from tt1;
ID NAME AGE
---------- ---------- ----------
1 a 10
2 b 20
6 100
4 40
5 50
SQL>
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19602/viewspace-1001303/ ,如需转载,请注明出处,否则将追究法律责任。