Oracle中mergeinto的操作方法

原创
小哥 3年前 (2022-10-29) 阅读数 48 #大杂烩

1.目的:

可以同时派生自1一个或多个源表更新、插入和删除目标表中的数据,通常用于操作大量数据,即。对于大量的数据更新,插入非常高效。

2.语法:

merge into table_name  alias1   --目标表 可以使用别名
using (table|view|sub_query) alias2      --数据源表 可以是表、视图或子查询。
on (join condition)   --关联条件
when matched then              --当关联条件成立时 更新、删除、插入where部分可选 
  --更新
  update  table_name set  col1=colvalue  where……
  --删除  
  delete from table_name  where  col2=colvalue  where……
--只能更新,不能删除 您也可以只删除而不更新。
--如果更新和删除同时存在,则删除条件必须在更新条件内,否则不能删除数据。
when not matched then      --当关联条件不成立时   
  --插入
  insert (col3) values (col3values)  where…… 
 when not matched  by source then      --当源表不存在时,存在目标表进行数据删除。
  delete; 

3.报表说明:

1、on当后续关联条件建立后,您可以update、delete。

2、on当后续关联条件不成立时,您可以。insert。

3当源表中没有数据而目标表中的数据可以删除时。

4.预防措施:
1只对“操作表”进行操作,源表不变。
2,不用放在update,delete,insert 操作是完整的,可以根据实际情况进行。
3、merge into它的效率很高,强烈推荐,特别是在一次性提交事务中,可以首先构建一个临时表,更新后可以清除数据。,这样update锁定手表的可能性非常小。
4、Merge语句还有一个强大的功能,那就是传递。OUTPUT子句,则可以输出刚刚更改的数据。我们在上面Merge添加AFTER语句OUTPUT子句。
5,可以使用TOP关键字限制操作目标表的行数,如图所示。8显示。如图3所示。2该语句将添加到TOP关键字,我们只看到两行更新。

5.示例:

1先看看这两块手表test_emp(表结构和emp相同,只是个别数据不同。),emp。

test_emp表:

emp表:

merge into 语句:

merge into test_emp  a   --须操作的桌子 可以使用别名
using emp b     
on (a.EMPNO = b.EMPNO)
when matched then              --当关联条件成立时 更新、删除、插入where部分可选 
  update set  a.sal= b.sal where a.empno = 7566 or a.empno = 7654
  delete where (empno = 7654)
when not matched then    
  insert (a.empno, a.ename, a.job, a.mgr, a.hiredate, a.sal, a.comm, a.deptno) 
  values (b.empno, b.ename, b.job, b.mgr, b.hiredate, b.sal, b.comm, b.deptno);

如果delete后面的where条件不能满足上述条件update的where条件,则不能删除数据。

merge into test_emp  a   --须操作的桌子 可以使用别名
using emp b     
on (a.EMPNO = b.EMPNO)
when matched then              --当关联条件成立时 更新、删除、插入where部分可选 
  update set  a.sal= b.sal where a.empno = 7566 
                                --or a.empno = 7654 如果您对此进行了评论,则无法删除数据。
  delete where (empno = 7654)
when not matched then    
  insert (a.empno, a.ename, a.job, a.mgr, a.hiredate, a.sal, a.comm, a.deptno) 
  values (b.empno, b.ename, b.job, b.mgr, b.hiredate, b.sal, b.comm, b.deptno);

empno = ‘7654‘,已被删除,起初没有删除,因为:但是,它还没有被删除 empno = ‘7654记录的原因是记录不满意。update在声明之后where条件。

最终结果test_emp如图:

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门