Thursday, July 2, 2009

Remove duplicate records from the table using CTE

Hello everyone,
I need to remove duplicate rows from the table and for that I made one query with CTE which will remove all duplicate rows from the table.
Here I put an example. So you can get better idea of it.

DROP TABLE DuplicateRcordTable
CREATE TABLE DuplicateRcordTable (Col1 INT, Col2 INT)
INSERT INTO DuplicateRcordTable
SELECT 1, 1
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4

SELECT * FROM DuplicateRcordTable


;with DuplicateRows
AS
(
SELECT *,ROW_NUMBER() over(partition by Col1,Col2 order by Col1) DuplicateRow FROM DuplicateRcordTable
)
DELETE FROM DuplicateRows where DuplicateRow>1

SELECT * FROM DuplicateRcordTable

RESULT:-
Before deleted duplicate records:-



After deleted duplicate records

No comments: