mysql seq 重置_需要在Oracle中重置序列的值
小編典典
如果使用該值,則不應(yīng)重置該值的原因:
如果你有20條記錄并刪除5-10條記錄會(huì)怎樣?中間有一個(gè)縫隙,無法重新設(shè)置序列。序列永遠(yuǎn)不會(huì)生成無間隙的數(shù)字序列,即完美的1、2 .. n。
如果你調(diào)用.nextval并且不使用該值,它就消失了。你要?jiǎng)h除并重新創(chuàng)建序列嗎?如果開始插入并取消插入,Oracle 將回滾所做的操作,這些值將消失。如果你設(shè)置了該選項(xiàng),nocache則差距將較小,但會(huì)降低性能。這值得么?
你的緩存應(yīng)設(shè)置為希望在所有會(huì)話中一次執(zhí)行的插入次數(shù),以避免任何性能問題。序列旨在提供一種非常快速,可擴(kuò)展的方式來創(chuàng)建代理密鑰,而無需任何鎖等,以免重新生成正整數(shù)集。
歸根結(jié)底,這絲毫沒有關(guān)系。如果你將不間斷的序列作為表的鍵,則你的數(shù)據(jù)而不是序列會(huì)出現(xiàn)問題。
回答問題:
要實(shí)際回答你的問題,你需要:
首先,找出表中的最大id(序列)值。
然后放下并重新創(chuàng)建序列。
找到最大值意味著你需要?jiǎng)討B(tài)地重新創(chuàng)建序列,而又要犧牲性能。
如果在這種情況下嘗試將某些東西插入表中,它將失敗,并且可能會(huì)使使用該序列的任何觸發(fā)器或其他對(duì)象無效:
declare
l_max_value number;
begin
select max(id)
into l_max_value
from my_table;
execute immediate 'drop sequence my_sequence_name';
-- nocache is not recommended if you are inserting more than
-- one row at a time, or inserting with any speed at all.
execute immediate 'create sequence my_sequence_name
start with ' || l_max_value
|| ' increment by 1
nomaxvalue
nocycle
nocache';
end;
/
正如我所說,不建議這樣做,你應(yīng)該忽略任何差距。
更新-又名更好的答案感謝Jeffrey Kemp:
正如杰弗里·肯普(Jeffrey Kemp)在評(píng)論中所建議的那樣,有一種與文檔建議相反的方法,該方法無需刪除并重新創(chuàng)建序列即可。
即,通過:
計(jì)算id表中的最大值與序列的當(dāng)前值之間的差。
更改順序以此負(fù)數(shù)遞增
更改順序以再次增加1。
這樣做的好處是對(duì)象仍然存在,并且觸發(fā)器,授權(quán)等也得以維護(hù)。如我所見,其不利之處在于,如果另一個(gè)會(huì)話與你的會(huì)話同時(shí)增加此負(fù)數(shù),則你可能退得太遠(yuǎn)。
這是一個(gè)示范:
設(shè)置測試:
SQL> create sequence test_seq
2 start with 1
3 increment by 1
4 nomaxvalue
5 nocycle
6 nocache;
Sequence created.
SQL>
SQL> create table tmp_test ( id number(16) );
Table created.
SQL>
SQL> declare
2 l_nextval number;
3 begin
4
5 for i in 1 .. 20 loop
6 insert into tmp_test values ( test_seq.nextval );
7 end loop;
8
9 end;
10 /
PL/SQL procedure successfully completed.
SQL>
SQL> select test_seq.currval from dual;
CURRVAL
----------
20
SQL>
SQL> delete from tmp_test where id > 15;
5 rows deleted.
SQL> commit;
Commit complete.
還原順序
SQL>
SQL> declare
2
3 l_max_id number;
4 l_max_seq number;
5
6 begin
7
8 -- Get the maximum ID
9 select max(id) into l_max_id
10 from tmp_test;
11
12 -- Get the current sequence value;
13 select test_seq.currval into l_max_seq
14 from dual;
15
16 -- Alter the sequence to increment by the difference ( -5 in this case )
.
17 execute immediate 'alter sequence test_seq
18 increment by ' || ( l_max_id - l_max_seq );
19
20 -- 'increment' by -5
21 select test_seq.nextval into l_max_seq
22 from dual;
23
24 -- Change the sequence back to normal
25 execute immediate 'alter sequence test_seq
26 increment by 1';
27
28 end;
29 /
PL/SQL procedure successfully completed.
SQL>
SQL> select test_seq.currval from dual;
CURRVAL
----------
15
SQL>
2020-04-13
總結(jié)
以上是生活随笔為你收集整理的mysql seq 重置_需要在Oracle中重置序列的值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: serum血清序列号_图文教程 将ser
- 下一篇: mysql可以打开dbt么_dbt 基本