1. 程式人生 > >oracle一次插入多條資料(insert all)

oracle一次插入多條資料(insert all)

問題

公司的專案,有個功能每次使用需要向資料庫插入很多資料,導致頁面等待很長時間才有結果。
資料庫:oracle11g
id:採用sequence自增
每次迴圈,都會查詢一次sequence,然後insert一條資料,效能非常低。

改進

改成一次插入多條資料,id通過觸發器自動設定,不再每次先查詢sequence,效率提高非常多。

oracle一次插入多條的方法

在oracle裡面,不支援像mysql那樣直接在後面拼多個記錄。oracle中有兩種方法達到批量插入的效果:

方法一:採用union all拼接查詢方式

本文不做詳細介紹,可在網上檢視相關資料。

insert
into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE) select 8000,0,'Multi 8000',1 from dual union all select 8001,0,'Multi 8001',1 from dual

方法二:採用insert all的方式

由於insert all方式插入多條時,通過sequence獲取的值是同一個,不會自動獲取多個,所以id需要通過其他方式設定,(我這裡採用觸發器方式自動設定id)

1、建立測試表:

create table test_insert(
       data_id number
(10) primary key, user_name varchar2(30), address varchar2(50) )

data_id為主鍵,通過sequence產生主鍵值。

2、建立序列:

create sequence seq_test_insert 
minvalue 1
maxvalue 999999999999999999999999
start with 1
increment by 1
cache 20;

3、建立觸發器
通過觸發器自動給insert語句設定id值

create or replace trigger tr_test_insert
before
insert on test_insert for each row begin select seq_test_insert.nextval into :new.data_id from dual;
end;

4、插入測試資料:

insert all 
into test_insert(user_name,address) values('aaa','henan')
into test_insert(user_name,address) values('bbb','shanghai')
into test_insert(user_name,address) values('ccc','beijing')
select * from dual;

相當於下面三個insert into語句,但效能比單條高多了。

insert into test_insert(user_name,address) values('aaa','henan');
insert into test_insert(user_name,address) values('bbb','shanghai');
insert into test_insert(user_name,address) values('ccc','beijing');

需要注意的是,在insert all語句裡不能直接使用seq_test_insert.nextval,因為即便每個into語句裡都加上seq_test_insert.nextval也不會獲得多個值。

5、檢視測試資料

select * from test_insert;

結果如下圖:
這裡寫圖片描述

另外,insert all還支援往不同的表裡插入資料,如:

insert all 
into table1(filed1,filed2)values('value1','value2')
into table2(欄位1,欄位2,欄位3) values(值1,值2,值3)
select * from dual;