How do I reset a sequence in Oracle?

后端 未结 18 1487
天命终不由人
天命终不由人 2020-11-22 05:09

In PostgreSQL, I can do something like this:

ALTER SEQUENCE serial RESTART WITH 0;

Is there an Oracle equivalent?

18条回答
  •  没有蜡笔的小新
    2020-11-22 05:52

    There is another way to reset a sequence in Oracle: set the maxvalue and cycle properties. When the nextval of the sequence hits the maxvalue, if the cycle property is set then it will begin again from the minvalue of the sequence.

    The advantage of this method compared to setting a negative increment by is the sequence can continue to be used while the reset process runs, reducing the chance you need to take some form of outage to do the reset.

    The value for maxvalue has to be greater than the current nextval, so the procedure below includes an optional parameter allowing a buffer in case the sequence is accessed again between selecting the nextval in the procedure and setting the cycle property.

    create sequence s start with 1 increment by 1;
    
    select s.nextval from dual
    connect by level <= 20;
    
       NEXTVAL
    ----------
             1 
    ...
            20
    
    create or replace procedure reset_sequence ( i_buffer in pls_integer default 0)
    as
      maxval pls_integer;
    begin
    
      maxval := s.nextval + greatest(i_buffer, 0); --ensure we don't go backwards!
      execute immediate 'alter sequence s cycle minvalue 0 maxvalue ' || maxval;
      maxval := s.nextval;
      execute immediate 'alter sequence s nocycle maxvalue 99999999999999';
    
    end;
    /
    show errors
    
    exec reset_sequence;
    
    select s.nextval from dual;
    
       NEXTVAL
    ----------
             1 
    

    The procedure as stands still allows the possibility that another session will fetch the value 0, which may or may not be an issue for you. If it is, you could always:

    • Set minvalue 1 in the first alter
    • Exclude the second nextval fetch
    • Move the statement to set the nocycle property into another procedure, to be run at a later date (assuming you want to do this).

提交回复
热议问题