Monday, July 26, 2010

How to delete duplicate records from SQL Server table

This can be done in 4 simple steps, utilizing temp tables.

First you need to identify duplicate records and insert them into a temp table:


INSERT INTO #mytemptbl
SELECT * FROM Table1
GROUP BY field1, field2, field3
Having COUNT(*) > 1


Then delete those records from the original table:


DELETE FROM Table1
FROM Table1
INNER JOIN #mytemptbl
ON Table1.field1 = #mytemptbl.field1
AND Table1.field2 = #mytemptbl.field2
AND Table1.field3 = #mytemptbl.field3


Next re-insert records from temp table into the original table:


INSERT INTO Table1
SELECT * FROM #mytemptbl



And finally drop temp table:


DROP TABLE #mytemptbl

No comments:

Post a Comment