1. 程式人生 > >oracle插入時如何自動生成主鍵

oracle插入時如何自動生成主鍵

oracle中自動生成主鍵方式例子如下:

1)先建立表:

create table student(

sno int not null,

sname varchar(20),

sex char(4),

constraint PK_SNO primary key(sno) );

2)建立序列:

create sequence seq_student --序列名

start with 1 --初始化為1

increment by 1 --每次增加1

maxvalue 99999 --最大值

nocache --無快取

nocycle --無迴圈,一直累加

3)這個時候插入資料:insert into student(sno,sname,sex) values(seq_student.nextval,'shang','男'),如果還想插入資料時主鍵自動加入則需要建立觸發器:

create or replace trigger tri_student

before insert on student for each row

declare

begin

if :new.sno is null or :new.sno=0 then

select seq_student.nextval into :new.sno from sys.dual; --seq_student為上面建的序列

end if;

end tri_studnet;(此中的if語句可以去掉)

4)測試語句:insert into student(sname,sex) values('test,'男');

如果報“觸發器無效且未通過重新驗證”可能是觸發器建的有問題