Tuesday, January 20, 2009

SQL: Duplicate Rows

This Query will delete duplicate records, not all the records, for examples if 3 duplicate rows exists in a table, this query delete 2 records and keep 1 rows



SET ROWCOUNT 1

DELETE yourtable
FROM yourtable a
WHERE
(SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
WHILE @@rowcount > 0
DELETE yourtable
FROM yourtable a
WHERE
(SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
SET ROWCOUNT 0


No comments:

Post a Comment