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
EmpId EmpName
E001GAGAN
E001GAGAN
E001GAGAN
E002AMAN
E002AMAN
E003NAMAN

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

Popular posts from this blog

FastEndpoint vs Minimal APIs vs Controller

Workflow Orchestration Tools (Stateless vs Workflow Core vs Elsa vs Step Functions vs Hangfire)

AutoMapper vs FastMapper