(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