2017-08-04 74 views
1

在我的表中,我需要在另一個表中插入重複的記錄。我需要從第一個表中刪除它。SQL - 插入重複行到新表,然後刪除重複記錄

而且我發現的代碼是這樣的:

WITH q AS 
(
    SELECT a.* FROM SampleData AS a 
    LEFT JOIN SampleData AS b ON 
    a.Name = b.Name AND 
    a.Account= b.Account AND 
    a.Amount = -b.Amount 
    WHERE b.Name IS NOT NULL 
) 
DELETE FROM q OUTPUT DELETED.* INTO SampleData2 

現在的問題是,它返回一個錯誤:

View or function 'q' is not updatable because the modification affects multiple base tables.

任何幫助?我無法找到解決此錯誤的方法。

回答

3

嘗試使用EXISTS

WITH q AS 
(
    SELECT a.* 
    FROM SampleData AS a 
    WHERE EXISTS (SELECT 1 
        FROM SampleData AS b 
        WHERE a.Name = b.Name 
        AND a.Account= b.Account 
        AND a.Amount = -b.Amount) 
) 
DELETE FROM q OUTPUT DELETED.* INTO SampleData2 
+0

。回覆晚了非常抱歉。它很棒!非常感謝你 – Jomari

+0

記得使用綠色勾號接受答案 –

0

嘗試像這樣...

WITH q 
AS (SELECT 
     a.* 
    FROM 
     SampleData AS a 
     LEFT JOIN SampleData AS b 
      ON a.Name = b.Name 
      AND a.Account = b.Account 
      AND a.Amount = - b.Amount 
    WHERE 
     b.Name IS NOT NULL 
) 
DELETE s 
    OUTPUT Deleted.* INTO Sample2 
FROM 
    SampleData s 
    JOIN q 
     ON s.Name = q.Name 
     AND s.Account = q.Account; 
0

我想下面的CTE挑選出重複的:

WITH q AS 
(
SELECT a.* FROM SampleData AS a 
LEFT JOIN SampleData AS b ON 
a.Name = b.Name AND 
a.Account= b.Account AND 
a.Amount = -b.Amount 
WHERE b.Name IS NOT NULL 
) 

SELECT * INTO NEWTABLE FROM q --Takes duplicates from CTE and inserts into a table called NEWTABLE 

DELETE FROM FIRST_TABLE 
WHERE NEWTABLE.Column = FIRST_TABLE.Column --Or whatever matches to help you delete the duplicates 

希望這有助於!