如何将Oracle DB中的所有序列重置为0?

时间:2019-02-01 10:45:44

标签: oracle sequence reset

我想将所有序列重置为0。这不起作用。你能说为什么吗?

create or replace
procedure reset_seq( p_seq_name in varchar2 )
is
    l_val number;
begin
    execute immediate
    'select ' || p_seq_name || '.nextval from dual' INTO l_val;

    execute immediate
    'alter sequence ' || p_seq_name || ' increment by -' || l_val || 
                                                          ' minvalue 0';

    execute immediate
    'select ' || p_seq_name || '.nextval from dual' INTO l_val;

    execute immediate
    'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
end;
/

此脚本来自堆栈溢出,适用于单个序列。

begin
for i in (select sequence_name from dba_sequences where sequence_name like '%SEQ_PR%') LOOP
execute immediate 'reset_seq('||i.sequence_name||')';
end loop;
end;
/

这是我自己写的:)

错误报告- ORA-00900:无效的SQL语句 ORA-06512:在第3行 00900. 00000-“无效的SQL语句”

1 个答案:

答案 0 :(得分:2)

您不需要动态SQL。

begin
for i in (select sequence_name from dba_sequences where sequence_name like '%SEQ_PR%') LOOP
  reset_seq(i.sequence_name);           --> this is just fine
end loop;
end;
/

示例(我改用USER_SEQUENCES

SQL> select seq_pr1.nextval from dual;

   NEXTVAL
----------
         9

SQL> select seq_pr2.nextval from dual;

   NEXTVAL
----------
         8

SQL> begin
  2  for i in (select sequence_name from user_sequences where sequence_name like '%SEQ_PR%') LOOP
  3    reset_seq(i.sequence_name);
  4  end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

SQL> select seq_pr1.nextval from dual;

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

SQL> select seq_pr2.nextval from dual;

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

SQL>