如何在不删除oracle中的序列的情况下更改序列顺序

时间:2018-07-20 13:18:59

标签: sql oracle plsql sequence

我当前的序列号是203,我需要跳到1203而不删除该序列。

3 个答案:

答案 0 :(得分:3)

您可以在所需的DB模式上创建这样的过程,如下所示:

SQL>Create or Replace Procedure Pr_Set_Sequence( i_seq_name varchar2, i_val pls_integer ) is
   v_val     pls_integer;
begin
  for c in (
            Select u.sequence_name seq
              From User_Sequences u
             Where u.sequence_name = upper(i_seq_name)
           ) 
  loop  
    execute immediate 'select '||i_seq_name||'.nextval from dual' INTO v_val;
    execute immediate 'alter sequence '||i_seq_name||' increment by ' ||
                                               to_char(-v_val+i_val) || ' minvalue 0';
    execute immediate 'select '||i_seq_name||'.nextval from dual' INTO v_val;
    execute immediate 'alter sequence '||i_seq_name||' increment by 1 minvalue 0';
  end loop;  
end;

并调用所需的值(在我的情况下,创建一个名为my_seq的新值):

SQL> create sequence my_seq;

Sequence created

SQL> select my_seq.nextval from dual;

   NEXTVAL
----------
         1

SQL> begin
  2     pr_set_sequence('my_seq',1203);
  3  end;
  4  /

PL/SQL procedure successfully completed

SQL> select my_seq.currval from dual;

   NEXTVAL
----------
      1203

答案 1 :(得分:2)

首先更改序列增量,假设您将203改为1203,我将添加1000,并进行适当调整。

ALTER SEQUENCE yourSequence INCREMENT BY 1000;

然后请求一个值

SELECT yourSequence.NextVal FROM dual;

然后将其更改回递增1(假设首先是1)

ALTER SEQUENCE yourSequence INCREMENT BY 1;

如果序列正在使用中,您真的不希望这样做-因为它可能会跳上几千个。

答案 2 :(得分:0)

只需执行WHILE循环,从序列中进行选择,直到达到所需的值即可。相当快。

declare
  v_sequence_value       number;
begin
  while v_sequence_value <= 1203 loop
    select my_sequence.nextval into v_sequence_value from dual;
  end loop;
end;
/