赞
踩
在Oracle里面,不支持像mysql那样直接在后面拼多个记录。Oracle中有两个方法达到批量插入的效果
- 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方式插入多条时,通过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语句设置值
- 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 all语句里不能直接使用seq_test_insert.nextval,因为即便每个into语句里都加上seq_test_insert.nextval也不会获得多个值。
另外,insert all还支持往不同的表里插入数据,如:
- insert all
- into table1(filed1,filed2)values('value1','value2')
- into table2(字段1,字段2,字段3) values(值1,值2,值3)
- select * from dual;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。