使用Sequence.nextVal插入全部生成唯一约束违规

时间:2018-04-16 16:39:21

标签: sql oracle11g

为什么此查询会抛出错误:

  

错误报告 -   ORA-00001:违反了唯一约束(ON24MASTER.LANGUAGE_CODE_PK)

查询

img {
  width: 100%;
  max-height: 100%;
  object-fit: fill;
}

考虑INSERT ALL INTO LANGUAGE_CODE(language_code_id,label,language_cd,country_cd,is_elite) VALUES(SEQ_LANGUAGE_CODE_ID.NEXTVAL,'Abkhazian','ab',NULL,'N') INTO LANGUAGE_CODE(language_code_id,label,language_cd,country_cd,is_elite) VALUES(SEQ_LANGUAGE_CODE_ID.NEXTVAL,'Afar','aa',NULL,'N') INTO LANGUAGE_CODE(language_code_id,label,language_cd,country_cd,is_elite) VALUES(SEQ_LANGUAGE_CODE_ID.NEXTVAL,'Afrikaans','af',NULL,'N') INTO LANGUAGE_CODE(language_code_id,label,language_cd,country_cd,is_elite) VALUES(SEQ_LANGUAGE_CODE_ID.NEXTVAL,'Akan','ak',NULL,'N') SELECT 1 FROM DUAL; = 198且db中的最新ID为180;

有什么问题?我可以不将select seq_language_code_id.nextval from dual;insert all一起使用吗?

1 个答案:

答案 0 :(得分:0)

不,你不能用INSERT ALL做到这一点。看看发生了什么:

SQL> create sequence seqa;

Sequence created.

SQL> create table test (id number);

Table created.

SQL> insert all
  2    into test values (seqa.nextval)
  3    into test values (seqa.nextval)
  4    into test values (seqa.nextval)
  5    into test values (seqa.nextval)
  6  select * from dual;

4 rows created.

SQL> select * From test;

        ID
----------
         1
         1
         1
         1

SQL>

请参阅?所有NEXTVAL都是相同的 - 在您的情况下 - 导致主键违规,这意味着您必须运行单独的INSERT INTO语句:

SQL> insert into test values (seqa.nextval);

1 row created.

SQL> insert into test values (seqa.nextval);

1 row created.

SQL> insert into test values (seqa.nextval);

1 row created.

SQL> select  * From test;

        ID
----------
         1
         1
         1
         1
         2
         3
         4

7 rows selected.

SQL>