Wednesday, November 19, 2008

The row value(s) updated or deleted either do not make the row unique or they alter multiple rows.

This is not a common error to see in the context of today's world, but it is really annoying when it does come up.

This morning while working on a SQL Table, I got this error to come up when I inserted a new row to a table. It did not complain to me when I did an insert on that table, but when I tried to update a few values in that newly added row, it threw up this error.

After a further look down into the issue, I noticed that the table did not had a Primary Key and therefore it allowed me to enter the duplicate records.

Now using SQL Server Management Studio, when I tried to update that row, this error showed up.

Now the worst part, it would not even let you delete that row from the table, since it gets confused which row to delete as there are two rows with exactly same values in the DB.

So below are the two methods to get rid of such an issue.

1. Use "SET ROWCOUNT = 1" when deleting the row.
When you do a
DELETE FROM Table1 where Name = 'ABCD'

it will not work since there are two rows with the value of Name = 'ABCD'
So by simple doing
SET ROWCOUNT = 1
DELETE FROM Table1 where Name = 'ABCD'

it works as it now looks for the first row that matches the criteria and deletes that.

2. Adding an Identity Column
Another way of tackling this problem is adding a new temporary Identity column that would serve as Primary key and we could safely delete the row based on that PK.
ALTER TABLE Table1
ADD TempPKID INT IDENTITY(1, 1)

This will give seperate identity values to both the rows and thus one of them could be deleted by using this column in the where clause.

6 comments:

  1. Anonymous13:28

    Ultimate!!!!!
    this Working

    ReplyDelete
  2. Anonymous18:48

    I was struggling to delete 3 rows for days... Solved by this advice and using tempPKID.


    TNX!!!

    ReplyDelete
  3. Awesome..Thanks a lot man

    ReplyDelete
  4. Anonymous03:11

    Fantastic!!

    ReplyDelete