oracle大批量數據更新


View Code
 1 比如現在對一個表增加一個流水字段,非空,唯一。  
 2 該表數據量為3000000.  
 3 假設表名為test。  
 4   
 5  1.使用cursor。  
 6  declare  
 7      cursor c_test  is  select rowid  from test;  
 8     v_test c_test %rowtype;  
 9  begin  
10      open c_test;  
11     loop  
12          fetch c_test  into v_test;  
13          exit  when c_test %notfound;  
14          update test  set sn  = test_seq.nextval;  
15      end loop;  
16      close c_test;  
17  end;  
18   
19  2.使用between ... and。  
20  declare  
21     -- 總的記錄數  
22     v_total  number( 14, 0) : =  0;  
23     -- 當前記錄index  
24     v_curr  number( 14, 0) : =  0;  
25     -- 記錄上一次更新的位置  
26     v_pri  number( 14, 0) : =  0;  
27  begin  
28      -- 查出總共的記錄數。  
29       select  count( *from test  into v_total;  
30      for i  in  1..v_total loop  
31     v_curr : = v_curr  +  1;  
32          if v_curr mod  100000  =  0  then  
33              update test  set sn  = test_seq.nextval  where rownum  between v_pri  and v_curr;  
34          end  if;  
35          -- 下一次更新開始的位置就是本次更新結束的位置  
36          v_pri : = v_curr;  
37      end loop;  
38   
39      -- 需要處理最后一部分數據,因為是100000次一提交,可能最后一部分不足100000,需要單獨處理。  
40       update test  set sn  = test_seq.nextval  where rownum  between v_pri  and v_total;  
41  end;  
42   
43  3.每一次更新都會查目前沒有更改的記錄數。  
44  declare  
45      -- 目前表中沒有更改的記錄數  
46      v_not_updated_count  number( 14, 0) : =  0;  
47  begin  
48     loop  
49          select  count( *into v_not_updated_count  from test  where sn  is  null;  
50          update test  set sn  = test_seq.nextval  where rownum  <=  100000  and sn  is  null;  
51          exit  when v_not_updated  =  0;  
52      end loop;  
53  end;  
54   
55   
56 效率比較:  
57 1和2可能效率差不多。大概要1個半小時。  
58 3需要10分鍾左右。


免責聲明!

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



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