Wednesday, March 10, 2010

Remove Duplicate Records From Table With Sql Server 2005

--FOR CREATING TABLE USE THIS QUERY

CREATE TABLE Duplicate(
ID INT,
FNAME VARCHAR(10),
MNAME VARCHAR(10)
)

--FOR INSERT VALUES IN CREATED TABLE USE THIS QUERY

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')

--FOR DISPLAY ALL RECORDS USE THIS QUERY

SELECT * FROM Duplicate

--FOR SELECT DUPLICATE DATA USE THIS QUERY

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 > 1

--FOR DELETE DUPLICATE DATE USE THIS QUERY

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

No comments: