当前位置:   article > 正文

Oracle sql批量插入多条数据_oracle批量添加数据sql

oracle批量添加数据sql

Oracle中一次插入多条的方法

在Oracle里面,不支持像mysql那样直接在后面拼多个记录。Oracle中有两个方法达到批量插入的效果

方法一:采用union all拼接查询方式

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

方法二:采用insert all的方式

由于insert all方式插入多条时,通过sequence获取的值是同一个,不会自动获取多个,所以id需要通过其他方式设置,(我这里采用触发器方式自动设置id)

1、创建测试表

  1. create table test_insert(
  2.        data_id number(10) primary key,
  3.        user_name varchar2(30),
  4.        address varchar2(50)
  5. )

data_id为主键,通过sequence产生主键值

2、创建序列

  1. create sequence seq_test_insert 
  2. minvalue 1
  3. maxvalue 999999999999999999999999
  4. start with 1
  5. increment by 1
  6. cache 20;

3、创建触发器

通过触发器自动给insert语句设置值

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

4、插入数据

  1. insert all 
  2. into test_insert(user_name,address) values('aaa','henan')
  3. into test_insert(user_name,address) values('bbb','shanghai')
  4. into test_insert(user_name,address) values('ccc','beijing')
  5. select * from dual;

需要注意的是,在insert all语句里不能直接使用seq_test_insert.nextval,因为即便每个into语句里都加上seq_test_insert.nextval也不会获得多个值。

 

另外,insert all还支持往不同的表里插入数据,如:

  1. insert all 
  2. into table1(filed1,filed2)values('value1','value2')
  3. into table2(字段1,字段2,字段3) values(值1,值2,值3)
  4. select * from dual;

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/871279
推荐阅读
相关标签
  

闽ICP备14008679号