Cannot Insert Duplicate Key Row in Object with Unique Index

I am trying to run the following query:

update OAR.oa_AcademicHead
set  personid=15857
where personid=1234

but I am getting the error:

Cannot insert duplicate key row in object 'OAR.oa_AcademicHead' with unique index 'IX_oa_AcademicHead_personid'.
The statement has been terminated.

What can be done to fix this??

2

4 Answers

A row where personid is 15857 already exists in the table. The unique index on that column is preventing you from committing another record with the same personid (an update is really a delete and insert).

You'll have to remove the existing person with that id first before running your query.*

* Disclaimer: make sure this is actually what you want to do; be aware of the issues it might cause.

2

I am aware that this question is really old. But still might be helpful.

I've experienced this problem with my database and managed to fix it after a few hours of struggling.

My database has an Attachments table, which has primary key ID. I also have messageID column and was not able to create two rows with same messageID. I have found that messageID is indexer. I don't know what are indexers used for exactly, but I simply deleted indexer and now it works fine.

If you get said error while using ASP.NET MVC do something like this:

db.Entry(personObject).State = EntityState.Modified;
db.Entry(personObject).Property(x => x.personid).IsModified = false;
db.SaveChanges();

If your model is decorated with an indexer like [Index(nameof(SomeForeignKey), nameof(SomeOtherForeignKey), IsUnique = true)], then you will counter problems like those, like "An error occurred while updating the entries. See the inner exception for details."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest