Oracle的批量插入和批量新增

1 引言

Oracle数据库对于大数据量的更新和插入如果一次一行SQL的写的话,显得有点low同时也是效率问题容易让人抓狂,因此在这里记叙下针对Oracle的批量更新和插入
建表:

-- 学生表
create table student (id varchar2(20),name varchar2(20),class varchar2(20));

-- 其他表
create table other (id varchar2(20),name varchar2(20));

1.1 批量更新

1.1.1 一般方式

update student s 
set s.name = 
(select o.name from other o where s.id = o.id )
where exists (select 1 from other o where s.id = o.id ) ;

引申问题:
针对上述的sql中的where条件可有可无,如果没了是全表更新,但是更新结果是需要匹配的上才更新,不然不更新,这样不容易看出实际更新了多少行;如果有where条件,就先去查证符合条件的再去更新,这样可以看出来更新了多少行

1.1.2 使用游标

由于一般的update更新耗时久,5W条数据能耗时12分钟,因此游标方式可以作为考虑

declare
 cursor my_cur is   --声明游标my_cur
 	select s.id,o.name from student s,other o where s.id = o.id ;
 count NUMBER;--声明一个number类型的变量
BEGIN count:=0;--初始化变量值为0
  FOR cur IN my_cur LOOP--遍历游标
   UPDATE student s SET s.name=cur.name WHERE s.id=cur.id;
       count:=count+1;--每次循环变量值+1
    IF(count>=1000) THEN
       COMMIT;
       count:=0;--每更新1000行,count值为1000时候,就提交给数据库提交后将变量归零,继续下一个1000行更新
    END IF;
  END LOOP;
   COMMIT;
END;
/

1.2 批量插入

一般批量插入方式与一般的插入语句是少了values关键字就可以使用批量插入了

insert into student 
       select o.*,'1' from other o

如果插入过多的话,可以使用游标的方式插入,来提高效率

posted @ 2021-01-12 18:20  上善若泪  阅读(1524)  评论(0编辑  收藏  举报