oracle插入时如何自动生成主键

来源:互联网 发布:js html data 编辑:程序博客网 时间:2024/04/30 11:31

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,'男');

如果报“触发器无效且未通过重新验证”可能是触发器建的有问题

原创粉丝点击