Oracle中为表设置自动增长的标识列

-- 创建序列
create sequence 序列名称
       start with 1 -- 起始值
       increment by 1 -- 增量
       maxvalue 99999999 -- 最大值
       nocycle -- 达到最大值后是否重新计算,当前为不重新计算,cycle为重新计算
       nocache; -- 不要缓存,容易跳号

-- 创建触发器
CREATE OR REPLACE TRIGGER 触发器名称
BEFORE INSERT ON 表名称 FOR EACH ROW
BEGIN
       SELECT 序列名称.NEXTVAL INTO :NEW.字段名称 FROM DUAL;
END;

说明:需要先建个序列,再建与此对应的触发器。最好每张表都这么建。
每次插入记录时就会自动向标识列中插值了。

测试代码:

--创建表
create table t_windturbine_day(id number primary key,createdate nvarchar2(25),
windturbinecode varchar(5),indicode number(5),indivalue varchar2(10),
passflage INTEGER default(0) );
--创建序列
create sequence seq_windturbine_day increment by 1 start with 1000000 
nomaxvalue nominvalue nocache ;
--创建触发器
create or replace trigger tr_windturbine_day 
  before insert on t_windturbine_day   for each row
begin   select seq_windturbine_day.nextval into :new.id from dual; end;
--插入数据
insert into t_windturbine_day(createdate,windturbinecode,indicode,indivalue)
values('20131108',18,10002,'3.95');
--通过这种方式插入,步长为1,但是id一次长2(第3条数)。为什么?我认为是触发器增长了1,
--seq_windturbine_day.nextval又增长了1所导致的。不知道对不对?
insert into t_windturbine_day(id,createdate,windturbinecode,indicode,indivalue)
values(seq_windturbine_day.nextval,'20131108',18,10002,'3.95');
--查询数据
select * from t_windturbine_day t;

 测试结果:

 

原文地址:https://www.cnblogs.com/wllzbky/p/3414372.html