I wrote a PL/SQL script to set a sequence's value to the maximum value of a table's primary key:
DECLARE
max_idn NUMERIC(18, 0);
seq_nextval NUMERIC(18, 0);
increment_amount NUMERIC(18, 0);
BEGIN
SELECT MAX(mbr_idn)
INTO max_idn
FROM mbr;
SELECT mbr_seq.nextval
INTO seq_nextval
FROM DUAL;
increment_amount := max_idn - seq_nextval;
EXECUTE IMMEDIATE
'ALTER SEQUENCE mbr_seq
increment by ' || increment_amount;
END;
However, I get an error if the sequence's MINVALUE is greater than the max primary key:
ORA-08004: sequence MBR_SEQ.NEXTVAL goes below MINVALUE and cannot be instantiated
ORA-06512: at line 10
What's the easiest way to say "increment the sequence by increment_amount, but don't go below MINVALUE"?