Remove Duplicate Records from SQL table

This Code will help to remove duplicate records when there is not key field in the table.
/* Create Table Statement */
CREATE TABLE #Employee
(
Name varchar(55) NULL,
Salary decimal(10, 2) NULL,
Designation varchar(20) NULL
 )

 /* Insert Data into the Table*/
 INSERT INTO #Employee VALUES('Lakhan Pal Garg', 10000, 'AST')
 INSERT INTO #Employee VALUES('Lakhan Pal Garg', 10000, 'AST')
 INSERT INTO #Employee VALUES('Amit Tyagi', 10000, 'ITA')
 INSERT INTO #Employee VALUES('Amit Tyagi', 10000, 'ITA')
 INSERT INTO #Employee VALUES('Lakhan Pal Garg', 12000, 'AST')
 INSERT INTO #Employee VALUES('Amit Tyagi', 13000, 'ITA')
 INSERT INTO #Employee VALUES('Sumit Sharma', 15000, 'AST')
 INSERT INTO #Employee VALUES('Sumit Sharma', 15500, 'AST')
 
/* Mark Duplicate Record */
WITH TempEmp (Name,duplicateRecCount)
AS
(
SELECT Name,ROW_NUMBER() OVER(PARTITION by Name, Salary, Designation ORDER BY Name)
AS duplicateRecCount
FROM #Employee
)

/* Now Delete Duplicate Records */
DELETE FROM TempEmp
WHERE duplicateRecCount > 1

/* See updated table data */
Select * from #Employee 

0 comments: