oracle序列创建以后,如果想重置序列从 0 开始,逐渐递增1,可以采用如下存储过程:
1 create or replace 2 procedure reset_seq( p_seq_name in varchar2 ) 3 is 4 l_val number; 5 begin 6 execute immediate 7 'select ' || p_seq_name || '.nextval from dual' INTO l_val; 8 9 execute immediate 10 'alter sequence ' || p_seq_name || ' increment by -' || l_val || 11 ' minvalue 0'; 12 13 execute immediate 14 'select ' || p_seq_name || '.nextval from dual' INTO l_val; 15 16 execute immediate 17 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0'; 18 end;
存储过程创建以后,调用该存储过程,参数是要重置的序列名称:
call reset_seq(‘test_seq’);
使用下面的SQL语句查询需要重置的序列:
1 SELECT a.sequence_name 序列名称, 2 a.min_value 序列最小值, 3 to_char(to_number( a.max_value)) 序列最大值, 4 a.last_number 序列当前值, 5 CASE a.last_number WHEN 1 THEN '--不需要重置;' ELSE 6 'CALL seq_reset(''' || a.sequence_name || ''');' END 重置序列脚本, 7 'DROP SEQUENCE ' || a.sequence_name 删除序列脚本, 8 'RENAME ' || a.sequence_name || ' TO {newname}' 重命名脚本 9 FROM USER_SEQUENCES a WHERE a.last_number<>1 10 ORDER BY a.sequence_name ASC;
重置序列脚本这列查询出来的值就是调用存储过程重置序列的SQL语句,直接执行SQL将重置序列。