As in the question, how do I automatically reset an Oracle sequence\'s value back to 0 every year in Oracle 10g?
I\'m using the sequence to generate an identifier i
I have found that was best to create a trigger and a table. The table will contain the year and sequence for the year. The trigger gets the current year, verifies the table, if none registry found, then inserts a new one starting from 1. Otherwise, select the last and increments by one, updating the corresponding table.
The Table:
create table GDRDOCUMENTOSEQ
(
noano NUMBER(4),
noseq NUMBER(6)
)
;
alter table GDRDOCUMENTOSEQ
add unique (NOANO);
The Trigger:
CREATE OR REPLACE TRIGGER "GDRGUIARESSARCIMENTONODOC_BIR"
BEFORE INSERT ON GDR.GDRGUIARESSARCIMENTO
FOR EACH ROW
DECLARE
lNoAno number;
lNoSeq number;
lQtd number;
begin
SELECT EXTRACT(YEAR FROM SYSDATE) into lNoAno FROM DUAL;
SELECT COUNT(0)
INTO lQtd
FROM gdr.gdrdocumentoseq ds
WHERE ds.noano = lNoAno;
IF lQtd = 0 then
lNoSeq := 1;
INSERT INTO GDR.GDRDOCUMENTOSEQ (NOANO, NOSEQ) VALUES (lNoAno, lNoSeq);
else
SELECT nvl(max(ds.noseq), 0) + 1
INTO lNoSeq
FROM gdr.gdrdocumentoseq ds
WHERE ds.noano = lNoAno;
UPDATE GDR.GDRDOCUMENTOSEQ ds
SET ds.noseq = lNoSeq
WHERE ds.noano = lNoAno;
end if;
:new.nodocumento := SUBSTR(lNoAno, 3) || lpad(lNoSeq, 6, '0');
end;
I have this code running in production from 2016. Currenty state of the table is:
NOANO NOSEQ
2017 1411
2016 237