Thursday, January 14, 2010

Delete Duplicate records from a table in sql

DECLARE @Duplicate TABLE (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 INTO @Duplicate VALUES(3, ‘BCB’,'DGD’)

WITH CTE as(SELECT ROW_NUMBER() OVER(PARTITION BY ID, FName, MName ORDER BY (SELECT 1)) AS RowID,*FROM @Duplicate)

SELECT ID, FName, MNameFROM CTEWHERE RowID = 1

ref: http://blog.sqlauthority.com/2007/03/01/sql-server-delete-duplicate-records-rows/

http://www.databasejournal.com/features/mssql/article.php/3572301/RowNumber-function-in-SQL-Server-2005.htm

No comments:

Post a Comment