Oracle 批量插入記錄

來源:互聯網
上載者:User

這裡使用了PL/SQL的聯合數組.

我要將一組用'_'分隔的記錄插入資料庫,當然,這樣做只是為了方便從java調用預存程序進行批量插入.

 

先定義數群組類型和一個工具函數(用來分解字串):

 1 CREATE OR REPLACE PACKAGE qtone IS
 2     TYPE SUBSTR_ARRAY IS TABLE OF VARCHAR2(100 CHAR) INDEX BY BINARY_INTEGER;
 3 END;
 4 
 5 create or replace FUNCTION split_str(str in varchar2, delimiter in varchar2) RETURN qtone.SUBSTR_ARRAY is
 6         src_str varchar2(300 char) := '';
 7         prev_index integer := 1;
 8         next_index integer := 1;
 9         
10         retval qtone.substr_array ;
11         cnt INTEGER := 1;
12     BEGIN
13         --去掉開頭和結束的分隔字元
14         src_str := trim(both delimiter from str); 
15         while next_index != 0 loop
16             next_index := instr(src_str,delimiter,prev_index,1);
17             
18             if(next_index = 0) then
19                 retval(cnt) := substr(src_str,prev_index);
20                 cnt := cnt + 1;
21             else
22                 retval(cnt) := substr(src_str,prev_index,next_index - prev_index);
23                 cnt := cnt + 1;
24             end if;
25             
26             prev_index := next_index + 1;  
27         end loop;
28 
29         RETURN retval;       
30     end;

 

然後,做個簡單測試:

 1 CREATE TABLE test(
 2     name VARCHAR2(20 char),
 3     address VARCHAR2(50 char)
 4 );
 5 
 6 DECLARE
 7     names VARCHAR2(100 char) := 'ungshow_sweet_ting';
 8     addrs VARCHAR2(100 char) := 'GuangDong_ZheJiang_HuBei';
 9 
10     addr_array qtone.SUBSTR_ARRAY;
11     name_array qtone.SUBSTR_ARRAY;
12 
13     stmt VARCHAR2(100 char) := '';
14 BEGIN
15     name_array := split_str(names,'_');
16     addr_array := split_str(addrs,'_');
17 
18     stmt := 'insert into test(name,address) values(:name,:addr)';
19     IF(name_array.COUNT <> 0 AND name_array.COUNT = addr_array.COUNT ) THEN 
20         FOR i IN name_array.first..name_array.last LOOP
21             EXECUTE IMMEDIATE stmt USING name_array(i),addr_array(i);
22         END LOOP ;
23 
24         commit;
25     END IF ;
26 END ;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.