Click here to Skip to main content
15,881,757 members
Articles / Database Development / SQL Server
Alternative
Tip/Trick

How to remove duplicate rows in SQL Server 2005 when no key is present

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
22 Feb 2011CPOL 14.2K   2   3
Here is another solution:IF OBJECT_ID( 'tempdb..#TestTable' ) IS NOT NULL BEGIN DROP TABLE #TestTable ENDCREATE TABLE #TestTable ( Column1 varchar(1), Column2 int )INSERT INTO #TestTable VALUES ('A', 1);INSERT INTO #TestTable VALUES ('A', 1); --...
Here is another solution:

SQL
IF OBJECT_ID( 'tempdb..#TestTable' ) IS NOT NULL
    BEGIN
    DROP TABLE #TestTable
    END

CREATE TABLE #TestTable
    (
    Column1 varchar(1),
    Column2 int
    )

INSERT INTO #TestTable VALUES ('A', 1);
INSERT INTO #TestTable VALUES ('A', 1); -- duplicate
INSERT INTO #TestTable VALUES ('A', 1); -- duplicate
INSERT INTO #TestTable VALUES ('A', 2);
INSERT INTO #TestTable VALUES ('B', 1);
INSERT INTO #TestTable VALUES ('B', 2);
INSERT INTO #TestTable VALUES ('B', 2); -- duplicate
INSERT INTO #TestTable VALUES ('C', 1);
INSERT INTO #TestTable VALUES ('C', 2);

SELECT  *
FROM    #TestTable
ORDER
BY      Column1,
        Column2

;WITH dup AS
    (
    SELECT  [DuplicateID] = ROW_NUMBER() OVER(PARTITION BY Column1,Column2 ORDER BY Column1,Column2 )
    --,*
    FROM    #TestTable
    )
DELETE FROM dup
WHERE   [DuplicateID] > 1

SELECT  *
FROM    #TestTable
ORDER
BY      Column1,
        Column2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralVery good alternative :) Marked as accepted Pin
Wendelius4-Mar-11 8:47
mentorWendelius4-Mar-11 8:47 
GeneralReason for my vote of 5 nice trick Pin
Francesco Pasquesi1-Mar-11 5:07
Francesco Pasquesi1-Mar-11 5:07 
GeneralReason for my vote of 5 Great Query Sir Pin
ims.sanjay28-Feb-11 18:57
ims.sanjay28-Feb-11 18:57 
Reason for my vote of 5
Great Query Sir

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.