Sunday, September 18, 2011

Deleting Only Duplicate/Repeting Records in SQl Server Table.

Here is a Query which will help you to delete the duplicate record from a table.
Ex:
Table Name : Test
Table Content:
id name
===============
1 Ajit
2 Amit
3 Rana
4 Raj
5 Sonu
5 Sonu
==================
Here the last two records are duplicate, i want to delete the duplicate record only not both record.
===================
So here we go type the following Query.
===================

declare @tbl Table(id int,name varchar(50))
insert into @tbl(id,name)
select distinct * from Test
truncate table Test
insert into Test(id,name)
select id,name from @tbl
select * from test
=======================
Press F5 (Execute this query)
Now you can se that the duplicate record is deleted from the table.
==================
Description:
===========
Here I am creating one temporary table called @tbl and in that I am storing the distinct content of table called Test.
after that i am truncating Test table and then again inserting the records from Temporary table called @tbl.
==================
Enjoy.......
Ask me for more.......