oracle批量插入数据

oracle之批量插入


insert into STU 
       select 6 , 'lily', '123' FROM dual union 

       select 7 , 'licu', '123' FROM dual union

       select 8 , 'zhas', '456' FROM dual

oracle批量插入数据_第1张图片


项目中主键id常常通过sequence来自动生成,并不是手动输入,新建STU_SEQ的sequence


如果直接调用stu_seq.nextval则会报错,如下所示:

insert into STU 
       select stu_seq.nextval , 'lily', '123' FROM dual union 
       select stu_seq.nextval, 'licu', '123' FROM dual union
       select stu_seq.nextval , 'zhas', '456' FROM dual 


可以通过两种方法来解决:

1.创建函数来自动生成序列

create or replace function get_seq return number is
  id number;
begin
  select STU_SEQ.nextval into id from dual;
  return(id);
end get_seq;


insert into STU 
       select get_seq , 'lily', '123' FROM dual union 
       select get_seq , 'licu', '123' FROM dual union
       select get_seq , 'zhas', '456' FROM dual 


2.创建触发器来自动生成序列

CREATE OR REPLACE TRIGGER MY_TGR 
  BEFORE INSERT ON STU
  FOR EACH ROW
DECLARE 
  NEXT_ID NUMBER;
BEGIN 
  SELECT STU_SEQ.NEXTVAL INTO NEXT_ID FROM DUAL;
  :NEW.ID := NEXT_ID; 
END;


insert into STU(name, PASSWORD) 
       select  'lily', '12333' FROM dual union 
       select  'licu', '12333' FROM dual union
       select  'zhas', '45336' FROM dual 


你可能感兴趣的:(数据库)