August 22, 2001 07:22 PM

Deleting Duplicate Records

Rating: (0)
SQL Server Magazine
InstantDoc ID #21704
Editor's Note: Send your SQL Server questions and comments to SQL Server MVP Brian Moran at savvy@sqlmag.com.

Deleting Duplicate Records

I have a table containing a set of columns that are supposed to be unique but that have duplicate values, which Table 1 shows. I'd like to end up with a table that looks like this:

...This article is for paid Professional Members only.

Already a Professional Member? Please log in now:

NOT A PROFESSIONAL MEMBER? YOU CHOOSE:

Professional Membership

Monthly

Annual

VIP Membership

Monthly

Annual

Add a Comment

tttttttt

Anonymous User 7/14/2005 4:02:48 AM


you could get all distinct records to a temporary table, delete everything in the main table, then copy the distinct records back:

CREATE TABLE Dups (FirstName varchar(10), LastName varchar(10))
GO

INSERT INTO Dups VALUES ( 'Robert', 'Aide')
INSERT INTO Dups VALUES ( 'David', 'Koidl')
INSERT INTO Dups VALUES ( 'Hongbo', 'Li')
INSERT INTO Dups VALUES ( 'Robert', 'Aide')
INSERT INTO Dups VALUES ( 'David', 'Koidl')
INSERT INTO Dups VALUES ( 'Hongbo', 'Li')
INSERT INTO Dups VALUES ( 'Robert', 'Aide')
INSERT INTO Dups VALUES ('David', 'Koidl')
INSERT INTO Dups VALUES ('Hongbo', 'Li')
INSERT INTO Dups VALUES ('Robert', 'Aide')
INSERT INTO Dups VALUES ('David', 'Koidl')
INSERT INTO Dups VALUES ('Hongbo', 'Li')
GO

--CREATE A TEMPORARY TABLE THAT HAS THE SAME SCHEMA AS MAIN TABLE
create table #dupstemp (FirstName varchar(10), LastName varchar(10))
--NOW GET DISTINCT VALUE FROM MAIN TABLE
INSERT INTO #dupstemp select distinct * from dups
--DELETE EVERYTHING FROM MAIN TABLE
DELETE FROM dups
WHERE
EXISTS
(
SELECT
*
FROM
dups DupsInner
WHERE
DupsInner.FirstName = Dups.FirstName
AND DupsInner.LastName = Dups.LastName
)
GO

--NOW COPY DISTINCT VALUES BACK IN
INSERT INTO dups select * from #dupstemp

--VOILA
select * from dups

Anonymous User 4/19/2005 7:16:20 PM


What would be the best if you do not have a field with a unique number like the ID field.

Anonymous User 3/30/2005 2:46:35 AM


good

Anonymous User 12/14/2004 4:52:51 PM


good

Anonymous User 11/7/2004 9:59:43 PM


Your Comments (required):i receive duplicate mails in my outlook when i access my mailbox other locations of company.all locations are connected by leased line.i am not getting where the problem is ..??? fonly few of my users face this problem..where could be the problem? server or outlook

sopan6/28/2004 3:24:08 AM


This query is the best way in terms of performance for a large database query over internet?

Fernando5/19/2004 10:20:56 AM


You must log on before posting a comment.

Are you a new visitor? Register Here
GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS