Wednesday, June 15, 2011

Delete Duplicate Recods from a Table in SQL Server 2005

CREATE TABLE dbo.Dupes
(
    PK_Column INT IDENTITY(1,1),
    Dupe_String VARCHAR(32)
)



INSERT dbo.Dupes(Dupe_String)
    SELECT 'foo'
    UNION ALL SELECT 'foo'
    UNION ALL SELECT 'foo'
    UNION ALL SELECT 'bar'
    UNION ALL SELECT 'bar'
    UNION ALL SELECT 'splunge'
    UNION ALL SELECT 'splunge'
    UNION ALL SELECT 'mort'

SELECT * FROM dbo.Dupes


DELETE dbo.Dupes
    FROM dbo.Dupes d
    LEFT OUTER JOIN
    (
        SELECT Dupe_String, pk_column = MIN(PK_Column)
        FROM dbo.Dupes
        GROUP BY Dupe_String
    ) x
    ON d.pk_column = x.pk_column
    WHERE x.pk_column IS NULL

No comments:

Post a Comment