Oracle序列详解


1.基本语法
(1) 创建序列命
CREATE SEQUENCE [user.]sequence_name
[INCREMENT BY n]
[START WITH n]
[maxvalue n | nomaxvalue]
[minvalue n | nominvalue]
[CYCLE|NOCYCLE]
[CACHE|NOCACHE]
[ORDER|NOORDER]
;
INCREMENT BY: 指定序列号之间的间隔,该值可为正的或负的整数,但不可为0。序列为升序。忽略该子句时,缺省值为1。
START WITH:指定生成的第一个序列号。在升序时,序列可从比最小值大的值开始,缺省值为序列的最小值。对于降序,序列可由比最大值小的值开始,缺省值为序列的最大值。
MAXVALUE:指定序列可生成的最大值。
NOMAXVALUE:为升序指定最大值为1027,为降序指定最大值为-1。
MINVALUE:指定序列的最小值。
NOMINVALUE:为升序指定最小值为1。为降序指定最小值为-1026。
CYCLE:循环使用,用大最大值再返。 CACHE:指定cache的值。如果指定CACHE值,Oracle就可以预先在内存里面放置一些sequence,这样存取的快些。cache里面的取完后,oracle自动再取一组到cache。 使用cache或许会跳号, 比如数据库突然不正常down掉(shutdown abort),cache中的sequence就会丢失. 所以可以在create sequence的时候用nocache防止这种情况。
ORDER:顺序使用序列值。

(2) 更改序列
ALTERSEQUENCE [user.]sequence_name
[INCREMENT BY n]
[MAXVALUE n| NOMAXVALUE ]
[MINVALUE n | NOMINVALUE]
[CYCLE|NOCYCLE]
[CACHE|NOCACHE]
[ORDER|NOORDER]

(3) 删除序列
DROP SEQUENCE [user.]sequence_name;

2. 序列的使用
序列提供两个方法,NextVal和CurrVal。
NextVal:取序列的下一个值,一次NEXTVAL会增加一次sequence的值。
CurrVal:取序列的当前值。

但是要注意的是:第一次NEXTVAL返回的是初始值;随后的NEXTVAL会自动增加你定义的INCREMENT BY值,然后返回增加后的值。CURRVAL总是返回当前SEQUENCE的值,但是在第一次NEXTVAL初始化之后才能使用CURRVAL,否则会出错。


3.创建连续编号表 SEQUENCE + TRIGGER
3.1 创建表
create or replace table test_table
(
idd number(3),
named varchar2(20)
);
/

3.2 创建序列sequence_test_table_id:
create sequence "sequence_test_table_id" increment by 1 start with 1 minvalue 1 maxvalue 999 cycle nocache order;

3.3 创建触发器
要使用sequence,还必须用上oracle的triger(触发器)
create or replace trigger trigger_insert_sequence
before insert on test_table
referencing old as old new as new

*表明在向test_table插入每一行之前触发
for each row
begin
*读取sequence_test_table_id的下一个值赋给test_table的新idd
select sequence_test_table_id.nextval into :new.idd from dual; 

exception
when others then
-- consider logging the error and then re-raise
raise;
end trigger_insert_sequence

3.4 测试
insert into test_table(named) values(sysdate);

如果,我们希望序列包含更多的信息,比如日期等,以便日后做统计用,可以吗?
当然可以!

我们可以在triger那里打主意:)
比如我们要在序列里加上日期20030225xxx,后面的xxx表示是从序列里的来值。
先要更新表:
alter table test_table modify (id number(11) )   *扩展列宽
然后修改triger
create or replace trigger trigger_insert_sequence
before insert on test_table
referencing old as old new as new
for each row begin

select to_char(sysdate,'yyyymmdd')||lpad(sequence_test_table_id.nextval,3,'0') into :new.idd from dual; 


exception
when others then
-- consider logging the error and then re-raise
raise;
end trigger_insert_sequence

相关内容