2014-03-28 171 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没有函数来设置序列的值,所以你必须以迂回的方式来做更改序列的步长。 –