• oracle中insert all的用法


    oracle中insert all的用法

    现在有个需求:将数据插入多个表中。怎么做呢?可以使用insert into语句进行分别插入,但是在oracle中有一个更好的实现方式:使用insert all语句。
    insert all语句是oracle中用于批量写数据的 。insert all分又为无条件插入和有条件插入。

    一、表和数据准备

    --创建表
    CREATE TABLE stu(
       ID   NUMBER(3),
       NAME VARCHAR2(30),
       sex  VARCHAR2(2)
    );
    
    --删除表
    drop table stu;
    drop table stu1;
    drop table stu2;
    
    --向stu表中插入数据
    INSERT INTO stu(ID, NAME, sex) VALUES(1, '成都', '女');
    INSERT INTO stu(ID, NAME, sex) VALUES(2, '深圳', '男');
    INSERT INTO stu(ID, NAME, sex) VALUES(3, '上海', '女');
    
    --复制表结构创建表stu1,stu2
    CREATE TABLE stu1 AS SELECT t.* FROM stu t WHERE 1 = 2;
    CREATE TABLE stu2 AS SELECT t.* FROM stu t WHERE 1 = 2;
    --查询表
    select * from stu;
    select * from stu1;
    select * from stu2;
    

    二、insert all无条件插入

    将stu表中的数据插入stu1和stu2表中可以这样写

    insert all
        into stu1 values(id,name,sex)
    	into stu2 values(id,name,sex)
    	select id,name,sex from stu;
    

    三、insert all有条件插入

    有条件插入又分为两种:insert all when...和insert first when...

    • insert all when类型
    insert all
        when id=1 then
    	into stu1 values(id,name,sex)
    	when id=2 then 
        into stu2	values(id,name,sex)
        else
    	into stu1 values(id,name,sex)
    	select id,name,sex from stu;
    

    结果如下:

    • insert first when 类型
    insert first
     when id<=2 then 
     into stu1 values(id,name,sex)
     when id<=3 then
     into stu2 values(id,name,sex)
     select id,name,sex from stu;
    

    结果如下:

    四、insert all和insert first的区别

    insert first是考虑先后关系的,如果有数据满足第一个when条件又满足第二个when条件,则执行第一个then插入语句,第二个then就不插入。反之有数据不满足第一个when条件且满足第二个when条件,则数据会插入第二个条件下对应的表中,这也正是insert first与inset all的区别。
    简单来说就是all只要满足条件,就会插入,这个会造成重复插入;first只要有一个满足条件,后面的条件不再判断,不会造成重复插入。
    注意:insert all 无法支持序列插入,会导致两边不一致。

    五、参考博文

    (1) https://www.cnblogs.com/myrunning/p/4386004.html
    (2) https://blog.csdn.net/ghostgant/article/details/5700228
    (3) https://www.cnblogs.com/hrhguanli/p/3773020.html
    (4) https://www.cnblogs.com/shoshana-kong/p/9340391.html

  • 相关阅读:
    Java 程序流程语句
    Java 基本语法
    Java 环境搭建
    Spring事务管理
    AOP 与 Spring中AOP使用(下)
    python爬虫笔记之爬取足球比赛赛程
    python爬虫笔记之re.match匹配,与search、findall区别
    python爬虫笔记之re.compile.findall()
    python爬虫笔记之re.IGNORECASE
    跨站脚本攻击(selfxss)笔记(三)
  • 原文地址:https://www.cnblogs.com/jasonboren/p/12102490.html
Copyright © 2020-2023  润新知