2014-03-28 79 views
0

使用Oracle 11,並使用查詢/查詢(無存儲過程)我想更新我的序值:甲骨文更新序列值

biggest primary key in table + 1 

這是我有,但不可能結合這兩種:

select max("ID") from ACCOUNTS;  

ALTER SEQUENCE SEQ_ACCOUNTS INCREMENT BY "how to use here the max + 1"; 
+0

您不能在單個查詢中執行此操作。您可以執行一系列SQL語句。或者,您可以將這一系列SQL語句放入存儲過程或匿名PL/SQL塊中。 –

+0

@Justin Cave它不一定是單個查詢,我只是希望它沒有存儲過程 – Spring

+0

是否可以接受匿名PL/SQL塊?如果是這樣,只需要使用存儲過程並用'DECLARE'替換'CREATE OR REPLACE PROCEDURE << procedure name >> AS'。 –

回答

2

example of a stored procedure that resets a sequence value可以在另一個StackOverflow線程中找到。這聽起來像一個匿名的PL/SQL塊,你可以接受,而不是一個存儲過程。在這種情況下,可以進行一些小的修改...

declare 
    l_current_max number; 
    l_current_seq number; 
    l_tmp   number; 
begin 
    select max(id) 
    into l_current_max 
    from accounts; 

    select seq_accounts.nextval 
    into l_current_seq 
    from dual; 

    -- Set the nextval of the sequence to 0 
    execute immediate 
    'alter sequence seq_accounts increment by -' || l_current_seq || ' minvalue 0'; 

    -- Fetch a value of 0 
    execute immediate 
    'select seq_accounts.nextval from dual' 
    into l_tmp; 

    -- Set the nextval of the sequence to the current max 
    execute immediate 
    'alter sequence seq_accounts increment by ' || l_current_max || ' minvalue 0'; 

    -- Fetch the current max 
    execute immediate 
    'select seq_accounts.nextval from dual' 
    into l_tmp; 

    -- Set the nextval of the sequence to the current max + 1 
    execute immediate 
    'alter sequence seq_accounts increment by 1 minvalue 0'; 
end; 

你可以做一個單一的步驟同樣的事情,而不是順序設置爲0,然後在單獨的步驟目前最大,但我覺得它有點更清楚這樣做。

+0

@Spring沒有函數來設置序列的值,所以你必須以迂迴的方式來做更改序列的步長。 –