如何将 Oracle DB 中的所有序列重置为值 0?
Posted
技术标签:
【中文标题】如何将 Oracle DB 中的所有序列重置为值 0?【英文标题】:How can I reset all sequences in my Oracle DB to value 0? 【发布时间】:2019-02-01 10:45:44 【问题描述】:我想将所有序列重置为 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】:您不需要动态 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>
【讨论】:
以上是关于如何将 Oracle DB 中的所有序列重置为值 0?的主要内容,如果未能解决你的问题,请参考以下文章