Blogger Information
Blog 39
fans 2
comment 2
visits 50563
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Oracle中一次性插入多条数据
fighting的博客
Original
8475 people have browsed it

                                                             采用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;

注:

dual是一个虚拟表,用来构成select的语法规则,oracle保证dual里面永远只有一条记录。我们可以用它来做很多事情,如下:

1、查看当前用户,可以在 SQL Plus中执行下面语句

select user from dual;

2、用来调用系统函数

select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual;--获得当前系统时间

select SYS_CONTEXT('USERENV','TERMINAL') from dual;--获得主机名

select SYS_CONTEXT('USERENV','language') from dual;--获得当前locale

select dbms_random.random from dual;--获得一个随机数

3、得到序列的下一个值或当前值,用下面语句

select your_sequence.nextval from dual;--获得序列your_sequence的下一个值

select your_sequence.currval from dual;--获得序列your_sequence的当前值

4、可以用做计算器

select 7*9 from dual;



Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post