Search code examples
oracle11gbulkinsertsequences

oracle bulk insert fails because sequence does not increment automatically


I am trying to do multiple inserts into an oracle table with data rom another table and I also use a sequence. Something like this: http://www.dbforums.com/oracle/1626242-insert-into-table-sequence-value-other-table.html

Now..in the destination table there is a primary key on the column that is being populated by the sequence and it is giving me primary key violation. My guess is that the sequence.nextval is not working for some reason. Where is the error? This is my actual query:

    insert into xxxx  (col1, col2, col3, col4, col5)
  select SEQ_CNT.nextval, inner_view.*
    from (select col1, 26, 0, 'N'
    FROM  yyyy WHERE col_ID = 30 AND DELETED = 'N' ) inner_view;

Solution

  • It seems unlikely to me that the problem is that calling nextval on the sequence is not working. It is much more likely that some other process has inserted data in the table with primary key values greater than the values currently being returned from the sequence. If you

    SELECT seq_cnt.nextval
      FROM dual
    

    and compare that to the largest value of the primary key in the table

    SELECT max(col1)
      FROM xxxxx
    

    my wager is that the maximum value is greater than the nextval from the sequence. If that's the case, you'd generally want to reset the sequence to the current maximum value as well as figuring out how the problematic data got inserted so that the problem doesn't happen again in the future.