oracle批量update 轉


我個人覺得寫的很好

http://blog.csdn.net/wanglilin/article/details/7200201

需求:

將t2(t_statbuf)表中id和t1(T_Mt)表相同的記錄更新進t1表。

1.錯誤的寫法:

 1 update table_name t1 set (a,b,c)=( select a,b,c from table_name_2 t2 where t1.a=t2.a);  

這種寫法,會更新t1表中的所有行:如果t1.a=t2.a的,就更新t2中查出的記錄進t1;如果t1.a<>t2.a的,t1中的記錄會被更新成空(null)。

正確的寫法:

1 update table_name t1 set (a,b,c)=( select a,b,c from table_name_2 t2 where t1.a=t2.a)
2 where exists(select 1 from table_name_2 t2 where t1.a=t2.a);  

解析:

正確的寫法,就是在后面加了一句 where exists(select 1 from table_name_2 t2 where t1.a=t2.a);

這句話的意思是:如果存在t1.a=t2.a,就更新,否則,不更新,所以不會導致t1表中所有的記錄都被更新。

例:

update table_name_1 set (a,b) = (select 1,2 from dual where 1=2);

這個結果會把table_name_1中的記錄全部更新成空(null),因為后面1=2不成立。

總結:

update時,要弄清限定條件,要測試!

我的測試語句:

1 update my_time_test1 t1 set (MDATE,DISCRIPT) =(select MDATE,DISCRIPT from   
2 my_time_test t2 where t1.DISCRIPT=t2.DISCRIPT) where exists (select 1 from   
3 my_time_test t2 where t1.DISCRIPT=t2.DISCRIPT);  

我的業務語句:

1 update T_Mt t1 set (Stat,OStat,RptTime) =(  
2 select Stat,Stat,RptTime from t_statbuf t2 where t1.MsgId=t2.MsgId) where exists(  
3 select 1 from t_statbuf t2 where t1.MsgId=t2.MsgId);  --如果存在t1和t2相等的,就更新。不加where exists,是不管存不存在,都更新,不存在的,結果會被更新成空,但是那條記錄還在  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM