0% found this document useful (0 votes)
50 views1 page

Delete Duplicate From Table

This document contains two SQL statements to delete duplicate records from a table. The first statement deletes any records from the MyTable table where the ID is not the maximum ID for the combination of the DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3 columns. The second statement uses a common table expression (CTE) to assign a row number to records partitioned by the Col1 and Col2 columns, and then deletes any records where the row number is greater than 1 to keep only the first duplicate record.

Uploaded by

Suresh Mupparaju
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views1 page

Delete Duplicate From Table

This document contains two SQL statements to delete duplicate records from a table. The first statement deletes any records from the MyTable table where the ID is not the maximum ID for the combination of the DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3 columns. The second statement uses a common table expression (CTE) to assign a row number to records partitioned by the Col1 and Col2 columns, and then deletes any records where the row number is greater than 1 to keep only the first duplicate record.

Uploaded by

Suresh Mupparaju
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Delete Duplicate From Table DELETE FROM MyTable WHERE ID NOT IN ( SELECT MAX(ID) FROM MyTable GROUP BY DuplicateColumn1,

DuplicateColumn2, DuplicateColumn3) 2. WITH CTE (COl1,Col2, DuplicateCount) AS ( SELECT COl1,Col2, ROW_NUMBER() OVER(PARTITION BY COl1,Col2 ORDER BY Col1) AS DuplicateCount FROM DuplicateRcordTable ) DELETE FROM CTE WHERE DuplicateCount > 1

CTE: Common Table Expressions, or CTE, are a new construct introduced in Microsoft SQL Server 2005 that offer a more readable form of the derived table that can be declared once and referenced multiple times in a query. Moreover, CTEs can be recursively defined, allowing a recursive entity to be enumerated without the need for recursive stored procedures. In this article we'll examine the benefits, uses, and syntax of both recursive and non-recursive CTEs. Read on to learn more!

You might also like