Oracle:将序列设置为特定值[重复]
Posted
技术标签:
【中文标题】Oracle:将序列设置为特定值[重复]【英文标题】:Oracle: Setting sequence to a specific value [duplicate] 【发布时间】:2012-07-26 14:29:30 【问题描述】:我正在使用 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。
【问题讨论】:
【参考方案1】:所以我发现了问题。以下应该是 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;
它成功了!!
【讨论】:
【参考方案2】:您需要删除序列然后重新创建它,使用 STARTS WITH 子句分配初始值,例如:
CREATE SEQUENCE saas.ArtifactTypes_id_seq
START WITH 72;
此外,从序列中选择 NEXTVAL 会自动将其递增 1。
【讨论】:
以上是关于Oracle:将序列设置为特定值[重复]的主要内容,如果未能解决你的问题,请参考以下文章