8

我正在使用 liquibase 来管理我的架构。我有一堆插入语句。我已经硬编码了主 ID 号码。完成所有插入后,我想将序列值更改为比表中主键的最大值大 1。为此,我编写了如下所示的 PL/SQL。但是,当我执行时,select ArtifactTypes_id_seq.nextval from dual;它仍然递增 0。

SET SERVEROUTPUT ON SIZE 1000000
DECLARE
    sequence_id NUMBER;
BEGIN

    SELECT NVL(MAX(idArtifactType), 0) + 1 INTO sequence_id FROM ArtifactTypes;
    EXECUTE IMMEDIATE 'ALTER SEQUENCE saas.ArtifactTypes_id_seq INCREMENT BY ' || sequence_id;
    EXECUTE IMMEDIATE 'SELECT ArtifactTypes_id_seq.nextval FROM dual';
    EXECUTE IMMEDIATE 'ALTER SEQUENCE saas.ArtifactTypes_id_seq INCREMENT BY 1';
    DBMS_OUTPUT.put_line('Executed "ALTER SEQUENCE saas.ArtifactTypes_id_seq INCREMENT BY ' || sequence_id || '"');
END;
/

DBMS_OUTPUT 提供以下输出 -
Executed "ALTER SEQUENCE saas.ArtifactTypes_id_seq INCREMENT BY 71"

我错过了什么?我做错了吗?注意:我尝试从 SQLDeveloper 执行这些 SQL。

4

2 回答 2

10

所以我发现了这个问题。以下应该是 PL/SQL -

SET SERVEROUTPUT ON SIZE 1000000
DECLARE
    sequence_id NUMBER;
    temp_seq NUMBER;
BEGIN
    SELECT NVL(MAX(idArtifactType), 0) + 1 INTO sequence_id FROM ArtifactTypes;
    EXECUTE IMMEDIATE 'ALTER SEQUENCE saas.ArtifactTypes_id_seq INCREMENT BY ' || sequence_id;
    SELECT ArtifactTypes_id_seq.nextval into temp_seq FROM dual;
    EXECUTE IMMEDIATE 'ALTER SEQUENCE saas.ArtifactTypes_id_seq INCREMENT BY 1';
    DBMS_OUTPUT.put_line('Executed "ALTER SEQUENCE saas.ArtifactTypes_id_seq INCREMENT BY ' || sequence_id || '"');
END;
/

以下声明 -
EXECUTE IMMEDIATE 'SELECT ArtifactTypes_id_seq.nextval FROM dual';
已更改为
SELECT ArtifactTypes_id_seq.nextval into temp_seq FROM dual;

它成功了!

于 2012-07-26T14:50:33.860 回答
7

您需要删除序列,然后重新创建它,使用 STARTS WITH 子句分配初始值,例如:

CREATE SEQUENCE saas.ArtifactTypes_id_seq
  START WITH 72;

此外,从序列中选择 NEXTVAL 会自动将其递增 1。

于 2012-07-26T14:36:24.253 回答