Click here to Skip to main content
15,886,798 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to insert multiple rows in a table using sequence
but there is primary key violation.plz help
Posted

1 solution

Most likely you re-use the same value from the sequence.

If you're inserting data based on a select query, then use the sequence inside the select. So something like:
SQL
INSERT INTO MyTable (
   PrimaryKeyCol,
   SomeCol1,
   SomeCol2,
   ...)
SELECT
   MySequence.NextVal,
   SomeColumn,
   AnotherColumn,
   ...
FROM MyTable
WHERE ....


Addition:

If the sequence is ordered:
- run
SQL
select max(keycolumn) from yourtable;

- run
SQL
select sequence.nextval from dual;


now if the highest value in your table is for example 10 and the sequence.nextval returned 7, then execute
SQL
select sequence.nextval from dual;

3 times
 
Share this answer
 
v2
Comments
baadsahcool 25-Aug-12 5:04am    
i am using
insert into tablename(primarykey,col 1,col 2)
values
(sequence.nextval,'value 1','value 2')

please help in this context.
Wendelius 25-Aug-12 5:08am    
Okay, the sequence should take care of the uniqueness of the values. So the likeliest cause is that someone has added rows to that table without using the sequence or the sequence is altered or recreated.

Get the next value from the sequence by

select sequence.nextval from dual;

and compare it to the values in the table. If the sequence is ordered then you can for example run the nextval until you get the next non-existent value
baadsahcool 25-Aug-12 6:24am    
please elaborate your answer
Wendelius 25-Aug-12 6:35am    
See the updated answer
baadsahcool 25-Aug-12 8:02am    
can u please give me example

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900