Deleting duplicate records using CTE
Hi Guys, here i m going to explain how you can use CTE to delete duplicate records.
suppose you have a table, like:-
M_Emp
Now Execute following query to delete duplicate records
;WITH CteExample(EmpId , RowId)
AS
(
SELECT EmpId,ROW_NUMBER()OVER(Partition by EMPID ORDER by EMPID) RowId
FROM M_Emp
)
DELETE FROM CteExample WHERE RowId > 1
This query will delete all the duplicate records.
suppose you have a table, like:-
M_Emp
EmpId | EmpName |
E001 | GAGAN |
E001 | GAGAN |
E001 | GAGAN |
E002 | AMAN |
E002 | AMAN |
E003 | NAMAN |
Now Execute following query to delete duplicate records
;WITH CteExample(EmpId , RowId)
AS
(
SELECT EmpId,ROW_NUMBER()OVER(Partition by EMPID ORDER by EMPID) RowId
FROM M_Emp
)
DELETE FROM CteExample WHERE RowId > 1
This query will delete all the duplicate records.
Comments