1

SQL Server 2008 R2 では、2 つの重複する ID とレコードをテーブルに追加しました。最後の 2 つのレコードのいずれかを削除しようとすると、次のエラーが表示されます。

行の値が更新または削除されても、行が一意にならないか、複数の行が変更されます。

データは次のとおりです。

7   ABC         6
7   ABC         6
7   ABC         6
8   XYZ         1
8   XYZ         1
8   XYZ         4
7   ABC         6
7   ABC         6

最後の 2 つのレコードを削除する必要があります。

7   ABC         6
7   ABC         6

「上位 200 行を編集」機能を使用して最後の 2 レコードを削除しようとして、この重複 ID を削除しようとしましたが、上記のエラーが発生しました。

どんな助けでも大歓迎です。前もって感謝します:)

4

2 に答える 2

1

テーブルに他の列があるという手掛かりがまったくないため、データが 3 つの列 A、B、C にあると仮定すると、次を使用して 2 つの行を削除できます。

;with t as (
    select top(2) *
      from tbl
     where A = 7 and B = 'ABC' and C = 6
)
DELETE t;

これにより、条件に基づいて 2 つの行が任意に一致し、それらが削除されます。

于 2012-12-07T22:05:44.260 に答える
0

これは、多くの重複がある可能性があるテーブルで重複を削除するために使用するコードの概要です。

/* I always put the rollback and commit up here in comments until I am sure I have 
   done what I wanted. */
BEGIN tran Jim1 -- rollback tran Jim1 -- Commit tran Jim1; DROP table PnLTest.dbo.What_Jim_Deleted

/* This creates a table to put the deleted rows in just in case I'm really screwed up */
SELECT top 1 *, NULL dupflag 
  INTO jt1.dbo.What_Jim_Deleted --DROP TABLE jt1.dbo.What_Jim_Deleted
  FROM jt1.dbo.tab1;
/* This removes the row without removing the table */
TRUNCATE TABLE jt1.dbo.What_Jim_Deleted;

/* the cte assigns a row number to each unique security for each day, dups will have a
   rownumber > 1.  The fields in the partition by are from the composite key for the 
   table (if one exists.  These are the queries that I ran to show them as dups

SELECT compkey1, compkey2, compkey3, compkey4, COUNT(*) 
  FROM jt1.dbo.tab1
  GROUP BY compkey1, compkey2, compkey3, compkey4
  HAVING COUNT(*) > 1
  ORDER BY 1 DESC


*/
with getthedups as
  (SELECT *,
       ROW_NUMBER() OVER 
         (partition by compkey1,compkey2, compkey3, compkey4 
                          ORDER BY Timestamp desc) dupflag /*This can be anything that gives some order to the rows (even if order doesn't matter) */
     FROM jt1.dbo.tab1)
/* This delete is deleting from the cte which cascades to the underlying table 
   The Where is part of the Delete (even though it comes after the OUTPUT.  The
   OUTPUT takes all of the DELETED row and inserts them into the "oh shit" table,
   just in case.*/
DELETE 
  FROM getthedups 
  OUTPUT DELETED.* INTO jti.dbo.What_Jim_Deleted
  WHERE dupflag > 1

--Check the resulting tables here to ensure that you did what you think you did

/* If all has gone well then commit the tran and drop the "oh shit" table, or let it 
   hang around for a while. */
于 2013-02-11T16:21:35.917 に答える