To delete duplicate records from a table without any schema changes

To delete duplicate records from a table without any schema changes or temp tables.
You can use CTE.
In example below we have duplicate Class entries in class table, first we can generate rownumber in CTE then delete from CTE where rownumber>1

;
WITH    CTE
          AS ( SELECT   ROW_NUMBER() OVER ( PARTITION BY vchClassName ORDER BY intClassID DESC ) rn ,
                        vchClassName
               FROM     dbo.Class
             )
    DELETE  FROM CTE
    WHERE   rn > 1

By deleting records from CTE actual tables records are be deleted.

Comments

Popular posts from this blog

Grouping Sets, With Rollup and With Cube example

Adding Page brake aganist group values

To Get All the Names of tables and Databases their data have changed in last 24 Hours And Backup those databases