Oracle 数据库批量插入

创建表:

create table stu(

    id number(8),

    name varchar2(200),

    age number(5)

);

表stu2 表stu3 和 表stu4 数据结构和stu 都一样。

  1. 传统插入方式,逐条在表中插入数据,浪费时间。 values 必须有

insert into stu(id, name, age) values(1, 'test', 20);

    2. 利用select方式,切记不可加values 关键字,select语句括号可有可无,为了清晰,建议加上括号

          正确写法:insert into stu(id, name, age) (select 2, 'test2', 20 from dual);

          错误写法:  insert into stu(id, name, age) values(select 2, 'test2', 20 from dual);

 

3. 以并集方式批量插入数据

insert into stu(id, name, age) (select 1, 'test1', 10 from dual union all select 2, 'test2', 20 from dual);

 

由上面第2中方式插入表中数据,我们可以推出下面第3中情况插入数据

4.将其他的数据表插入到同一张表中

4.1 一般将一张表数据字段处理复制到另一张表中

insert into stu(id, name, age) (select t.field1, t.field2, t.field3|| t.field4 from B t);

 

4.2 将多张表数据复制到另一张表中

insert into stu(id, name, age) (select b.field1 id, b.field2 name, b.field3 age as id from B b union all select c.field1 id, c.field2 name, c.field3 age from C c union all select 3 id, test3 name, 30 age from dual);

这里要注意:1、数据表并集数据类型必须一致。表B的字段field1 field2 field3 和 表C的字段field1 field2 field3 以及 3, ‘test3’, 30 的数据类型必须一致,目前数据类型依次为整型,字符串,整型,否则并集失败。2、字段处理。通常需要将select表的字段需要简单处理进行插入。3、 字段顺序。select 查询语句的字段顺序 和 insert 字段顺序一致。  无论select的语句是否有字段别名于insert字段对应,都是以顺序为主,与名称无关。

5.给多张表插入数据

insert all

into stu2(id, name, age) values(1, test1, 11)

     into stu3(id, name, age) values(2, test2, 22)

select 1 from dual;

注意:这里select 1 from dual 语句不能缺少。

特殊场景1:当stu2 和 stu3 为同一张表是,也就是对一张表批量插入

insert all

into stu(id, name, age) values(2, 'test2', 22)

             into stu(id, name, age) values(3, 'test3', 33)

select 1 from dual;

特殊场景2:将stu表中数据复制到stu2 和 stu3 stu4 中:

insert all

             into stu2(id, name, age)

             into stu3(id, name, age)

             into stu4(id1, name1, age1)

select t.id, t.name, t.age from stu t;

 

文章若有错误,请批评指正,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值