什么是序列?
序列: 可供多个用户用来产生唯一数值的数据库对象
自动提供唯一的数值
共享对象
主要用于提供主键值
将序列值装入内存可以提高访问效率
注意:
将序列值装入内存可提高访问效率
序列在下列情况下出现裂缝:
回滚
系统异常
多个表同时使用同一序列
如果不将序列的值装入内存(NOCACHE), 可使用表 USER_SEQUENCES 查看序列当前的有效值
常用sql:
--创建sequence
create sequence s_test00
increment by 10 --每次增长10
start with 10--从10开始增长
maxvalue 100--提供的最大值
cycle--需要循环
nocache--不需要缓存登陆
NEXTVAL 和 CURRVAL 伪列:
NEXTVAL 返回序列中下一个有效的值,任何用户都可以引用.
CURRVAL 中存放序列的当前值.
NEXTVAL 应在 CURRVAL 之前指定 ,否则会报CURRVAL 尚未在此会话中定义的错误.
--使sequence往下叠加
select s_test00.nextval from dual;
--查询当前的sequence值
select s_test00.currval from dual;
--设置表的某列按照sequence增长
create table t_emp10 as select employee_id ,first_name , salary from employees where 1=2;
insert into t_emp10 values(s_test00.nextval , 'A',300);
--修改sequence
alter sequence s_test00
increment by 1
nocycle;
修改序列的注意事项:
必须是序列的拥有者或对序列有 ALTER 权限
只有将来的序列值会被改变
改变序列的初始值只能通过删除序列之后重建序列的方法实现
--删除序列
drop sequence e_test00;
怎样为Oracle表的某个字段设置为自增序列:
--创建表
create table customers
(
id int primary key,
name varchar(30) not null unique,
address varchar(30),
phone varchar(30)
);
--创建序列
create sequence customers_seq minvalue 1 maxvalue 99999999
increment by 1
start with 1
nocycle;
drop sequence dectuser_tb_seq;
给表添加自增序列
create or replace trigger customers_tirgger
before insert on customers /*触发条件:当向表dectuser执行插入操作时触发此触发器*/
for each row /*对每一行都检测是否触发*/
begin /*触发器开始*/
select customers_seq.nextval into :new.ID from dual; /*触发器主题内容,即触发后执行的动作,在此是取得序列dectuser_tb_seq的下一个值插入到表dectuser中的userid字段中*/
end;
commit;
insert into customers (name,address,phone) values('CuiC','BJ','18613376475');
select * from customers;
在开发中对于sequence容易出一下错误:
ORA-08002: 序列 SEQ_GX.CURRVAL 尚未在此会话中定义;
原因如下:在2个数据库连接函数中用序列.CURRVAL会得到上面的错误,所以要使用SEQ_table_BH.CURRVAL就需要在一个数据库连接中先使用序列.NEXTVAL,再使用序列.CURRVAL。