oracle实现插入数据时主键自增

在看ORACLE_PL/SQL实例精解的时候用到了student表,需要自己创建。

1  首先是建表语句

create table student (
       student_id number(8) not null primary key, --主键列
       first_name varchar2(50), -- 名字
       last_name varchar2(50)   -- 姓
);

2 创建自增序列

create sequence seq_student
       minvalue 1  --最小值
       nomaxvalue --最大值
       start with 1 --起始值
       increment by 1  --增长基数
       nocycle  --不循环,一直增加
       nocache ; -- 不使用缓存

到这里其实就可以使用了,只是在插入的时候必须要自己调用,像这样

insert into student(student_id,first_name,last_name) values(seq_student.nextval,'','');

为了可以不关注主键列,创建一个触发器。


3 创建触发器(插入数据时触发)

create trigger tri_student_ins 
       before insert on student for each row  when (new.student_id is null)
    begin 
      select seq_student.nextval into:new.student_id from dual;
    end;  

这样就可以插入数据了

insert into student(first_name,last_name) values('','');

4 写一个pl/sql代码块,批量插入数据

declare 
       i number := 1;
       v_first_name varchar2(50);
       v_last_name varchar2(50);
begin 
  for i in 1 .. 200 
    loop 
      v_first_name := '' || to_char(i);
      v_last_name := '' || to_char(i);
      insert into student(first_name,last_name) values(v_first_name,v_last_name);
      commit;
    end loop;
end;   

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值