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;

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

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
--创建表
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;

 测试结果:

 

2018年7月28日,绝望到明白人活着只能靠自己; 2018年7月29日,告诉她一切,还对我不离不弃。 从此,走技术路线,改变生活。
原文地址:https://www.cnblogs.com/outlooking/p/4265000.html