Friday 13 September 2013

How to delete duplicate record from the table in MS SQL.

In the previous article, I have explained how tofind duplicate records in the table in MS SQL.
In this article, I have explained how to delete duplicate records from the table in MS SQL.

First create a temporary table on which you can test.

Write the following query to create temporary table in MS SQL.

SELECT * INTO TempExamResult FROM ExamResult --TempExamResult is a name of temporary table which taking all data from ExamResult

Now you can play with this table freely.

Write the following query to find duplicate records in the table and delete it from the table.

WITH Duplicates AS
(
SELECT
     name,Marks,
     ROW_NUMBER() OVER( PARTITION BY Subject,name
          ORDER BY Subject,name DESC) AS Sus
FROM TempExamResult
)
DELETE Duplicates
WHERE Sus > 1


Now check the table records for surety that duplicate records deleted  from table or not.
After that drop temporary table.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.