Tuesday, May 31, 2011

Delete Duplicate Records in tables

CREATE TABLE #Duplicate (ID INT,FNAME VARCHAR(10),MNAME
)
VARCHAR(10)INSERT INTO #Duplicate VALUES(1, 'AAA','CCC')INSERT INTO #Duplicate VALUES(2, 'BBB','DDD')INSERT INTO #Duplicate VALUES(1, 'AAA','CCC')INSERT INTO #Duplicate VALUES(2, 'BBB','DDD')INSERT INTO #Duplicate VALUES(1, 'AAA','CCC')INSERT INTO #Duplicate VALUES(2, 'BBB','DDD')INSERT
 ---Otion 1
;WITH CTE as(SELECT
*
ROW_NUMBER() OVER(PARTITION BY ID, FName, MName ORDER BY (SELECT 1)) AS RowID,FROM #Duplicate)DELETE FROM CTE WHERE RowID > 1SELECT
 ---option 2
SELECT * INTO #TempDuplicate FROM #Duplicate WHERE 1 = 0INSERT #TempDuplicate SELECT DISTINCT * FROM #DuplicateBEGIN
DELETE
TRAN #DuplicateINSERT #Duplicate SELECT * FROM #TempDuplicateCOMMIT
DROP
TRAN TABLE #TempDuplicateSELECT * FROM #Duplicate
* FROM #Duplicate
INTO #Duplicate VALUES(3, 'BCB','DGD')

1 comment:

  1. SELECT * INTO #TempDuplicate FROM #Duplicate WHERE 1 = 0
    INSERT #TempDuplicate SELECT DISTINCT * FROM #Duplicate
    BEGIN TRAN
    DELETE FROM #Duplicate
    INSERT #Duplicate SELECT * FROM #TempDuplicate
    COMMIT

    Like this

    ReplyDelete