Oracle中一般将自增sequence重置为初始1时,都是删除再重建,这种方式有很多弊端,依赖它的函数和存储过程将失效,需要重新编译。
不过有两种巧妙的方式,不用删除,利用步长参数,先查出sequence的nextval,记住,把递增改为负的这个值(反过来走),然后再改回来。
删除重建的方法:
create or replace procedure Seq_reset(seqName in varchar) as
n_count number(8);
v_sql varchar(500);
v_code NUMBER;
v_errm VARCHAR2(64);
--mahongmin
begin
select count(1)
into n_count
from user_sequences t
where t.sequence_name = seqName;
if n_count > 0 then
execute immediate 'drop sequence ' || seqName;
end if;
v_sql := 'create sequence ' || seqName ||
' minvalue 1 maxvalue 99999999 start with 1 increment by 1 NOCYCLE cache 20';
execute immediate v_sql;
exception
when others then
v_code := SQLCODE;
v_errm := SQLERRM;
DBMS_OUTPUT.PUT_LINE('重置sequence时, Error code ' || v_code || ': ' ||
v_errm);
end;
方式1:
oracle重置序列从指定的值开始重置序列
例如从10000001开始序列
create or replace procedure seq_reset(v_seqname varchar2)
n number(10);
v_startnum number(10) := 10000001; --从多少开始
v_step number(10) := 1; --步进
tsql varchar2(200);
begin
execute immediate 'select ' || v_seqname || '.nextval from dual'
into n;
n := v_startnum - n - v_step; --从10000001开始
tsql := 'alter sequence ' || v_seqname || ' increment by ' || n;
execute immediate tsql;
execute immediate 'select ' || v_seqname || '.nextval from dual'
into n;
tsql := 'alter sequence ' || v_seqname || ' increment by ' || v_step;
execute immediate tsql;
end;
方式2:
假设需要修改的序列名:seq_name
1、select seq_name.nextval from dual; //假设得到结果5656
2、 alter sequence seq_name increment by -5655; //注意是-(n-1)
3、 select seq_name.nextval from dual;//再查一遍,走一下,重置为1了
4、 alter sequence seq_name increment by 1;//还原
可以写个存储过程,以下是完整的存储过程,然后调用传参即可:
create or replace procedure seq_reset(v_seqname varchar2)
as n number(10);
tsql varchar2(100);
begin
execute immediate 'select '||v_seqname||'.nextval from dual' into n;
n:=-(n-1);
tsql:='alter sequence '||v_seqname||' increment by '|| n;
execute immediate tsql;
execute immediate 'select '||v_seqname||'.nextval from dual' into n;
tsql:='alter sequence '||v_seqname||' increment by 1';
execute immediate tsql;
end seq_reset;
Test:
--创建序列
create sequence seq_test minvalue 1 maxvalue 99999999 start with 1 increment by 1 NOCYCLE cache 20;
--执行序列
select seq_test.nextval from dual;
--重置序列
call seq_reset(seq_test);