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

I came across an error today in SQL Server 2005. 

 

 

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

 

The reason I got this error was because I created a table for a data mapping application and in my haste I forgot to include a primary key.  I checked my table today and found records that were duplicated and whenever I tried to delete or edit a row in SQL Management Studio this error showed up.  So I knew I had to put a primary key in the database and in order to do that I had to take care of the duplication.  Below are 3 different ways I found to fix this problem.

 

Solution 1

The first solution is for getting rid of several duplicated rows.  This solution used multiple queries.

 

Step 1. 

     This query puts the duplicate keys in a separate table that this query creates.


SELECT col1, col2, col3=COUNT(*)

INTO HOLDKEY

FROM Table1

GROUP BY col1, col2

HAVING COUNT(*) > 1

 

Step 2. 

     This query creates another new table and just includes unique primary keys.

 

SELECT DISTINCT Table1.*

INTO HoldUps

FROM Table1, HoldKey

WHERE Table1.col1 = HoldKey.col1

AND Table1.col2 = HoldKey.col2

 

*Before step 3 check the HoldUps table for duplicates.  If you have duplicates in that table refer to the microsoft link below.

 

Step 3. 

     This query deletes the duplicate rows from the original table.

 

DELETE Table1

FROM Table1, HoldKey

WHERE Table1.col1 = HoldKey.col1

AND Table1.col2 = HoldKey.col2

 

Step 4. 

     This query inserts the unique rows from the Holdups table into the original table.

 

 INSERT Table1 SELECT * FROM Holdups

 

Step 5.

     Delete the two new tables that the queries created and you’re finished.

 

 

Solution 2

This solution is used for instances where you just need to delete one duplicate row.  Just use a delete statement like you would any time you delete a row.  The only difference is the SET ROWCOUNT 1 makes it so that only 1 row gets deleted.  Delete the 1 row and that takes care of the duplication.

 

SET ROWCOUNT 1

DELETE FROM Table1

WHERE col1 = ‘0001’

 

Solution 3

This solution is a yet another way to approach this problem.  In this approach you use the query below to create a new column that numbers your records 1, 2, 3, etc.  This will get rid of the duplication and allow you to delete the records or update them as you need.  After you fix the duplication problem, just remember to delete the column.

 

ALTER TABLE Table1

ADD TempID int IDENTITY(1, 1)

 

 

 

 

The microsoft link I found that led me to solution 1.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值