oracle 自增长字段

  oracle中,使用序列和触发器可以实现某个字段的自增长.具体过程...

  首先创建一张表

create table topic(
  tId number(5,0),--自增长字段
  tStr1 varchar2(10),--其他字段1
  tStr2 varchar2(10),--其他字段2
  tStr3 varchar2(10),--其他字段3  
);

 然后创建一个序列

create sequence topic_id_seq
increment by 1 --每次增加1
start with 1  
nomaxvalue --无最大值
nocycle; --不循环

 创建一个触发器

create or replace trigger topic_id_trigger 
before insert
on topic
for each row
begin
select topic_id_seq.nextval into :new.tId from dual;
end;

 完成后在向表topic中插入数据时,可以

insert into topic(tStr1, tStr2, tStr3) values('aaa', 'bbb' ,'ccc');
insert into topic(tStr1, tStr2, tStr3) values('aaa', 'bbb' ,'ccc');
insert into topic(tStr1, tStr2, tStr3) values('aaa', 'bbb' ,'ccc');

 这样topic表中的tId字段的值会一次被赋予1,2,3...

 也可以这样插入

insert into topic values(topic_id_seq.currval, 'aaa', 'bbb', 'ccc');

 关于sequence中的currval和nextval

  currval:返回当前序列的值;

  nextval:增加序列的值,然后返回序列的值;

  首次向表中插入数据时,不可以使用

insert into topic values(topic_id_seq.currval, 'aaa', 'bbb', 'ccc');

  当向表中插入一条数据以后才可以使用.

posted on 2012-04-16 22:07  碎雨  阅读(200)  评论(0编辑  收藏  举报

导航