Oracle存在则更新,不存在则插入应用

来源:互联网 发布:java面向对象知识点 编辑:程序博客网 时间:2024/06/17 07:24
更新同一张表的数据。需要注意下细节,因为可能涉及到using的数据集为null,所以要使用count()函数。
[sql] view plain copy
  1. MERGE INTO mn a  
  2. USING (select count(*) co from mn where mn.ID=4) b  
  3. ON (b.co<>0)--这里使用了count和<>,注意下,想下为什么!  
  4. WHEN MATCHED THEN  
  5. UPDATE  
  6. SET a.NAME = 'E'  
  7. where a.ID=4  
  8. WHEN NOT MATCHED THEN  
  9. INSERT  
  10. VALUES (4, 'E');  


不同表:
[sql] view plain copy
  1. --测试数据  
  2. create table table1(id varchar2(100),name varchar2(1000),address varchar2(1000));  
  3. insert into table1(id,name,address)values('01001','影子','河北') ;  
  4. commit;  
  5.   
  6. --插入  
  7. merge into table1 t1  
  8. using (select '01002' id,'影子' name,'河北' address from dual) t2  
  9. on (t1.id = t2.id)  
  10. when matched then  
  11.      update set t1.name = t2.name, t1.address = t2.address  
  12. when not matched then  
  13.      insert values (t2.id, t2.name,t2.address);  
  14. commit;  
  15.   
  16. --查询结果  
  17. select * from table1  
  18. 01001    影子    河北  
  19. 01002    影子2    辽宁  
  20.   
  21. --更新  
  22. merge into table1 t1  
  23. using (select '01001' id,'不是影子' name,'山西' address from dual) t2  
  24. on (t1.id = t2.id)  
  25. when matched then  
  26.      update set t1.name = t2.name, t1.address = t2.address  
  27. when not matched then  
  28.      insert values (t2.id, t2.name,t2.address);  
  29. commit;  
  30.   
  31.   
  32. --查询结果  
  33. select * from table1  
  34.   
  35. 01001    不是影子    山西  
  36. 01002    影子2    辽宁  
  37.   
  38. --删除测试数据  
  39. drop table table1;