1. 程式人生 > >oracle實現插入資料時主鍵自增

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;