I'm really new to pl/sql. I'm trying to do a Trigger like this one (adr = after delete row) but it seems that I can't use ALTER SEQUENCE. Is this the right way of decrementing after a row is deleted or should I use a procedure?
CREATE OR REPLACE TRIGGER adr_trg
AFTER DELETE ON table
FOR EACH ROW
BEGIN
ALTER SEQUENCE table_seq INCREMENT BY -1;
END;
Edit:
Sequence I'm using:
CREATE SEQUENCE table_seq INCREMENT BY 1 START WITH 1;
Trigger I'm using:
CREATE OR REPLACE TRIGGER bir_trg
BEFORE INSERT ON table
FOR EACH ROW
BEGIN
IF :new.id IS NULL
THEN
:new.id := table_seq.nextval;
END IF;
END bir_trg;
I might be "reading between the lines" here, but I suspect your aim here is that if you have 5 entries in the table populated by sequence.nextval, eg
ID
---
1
2
3
4
5
and then someone deletes row 5, you want to take the sequence back to a value of 4.
There's two things wrong with that:
What if someone deletes "3" ? You can't roll the sequence back by 2, because the moment you use seq=3 and move onto seq=4, you'll get a clash
You cannot guarantee no gaps with a sequence. All it would take is for someone to grab a sequence value, and then issue a rollback (or encounter any other kind of error in the transaction and that sequence value is gone forever)
Which brings me to the overriding question:
Why would you be worried about gaps anyway ?