Theme Graphic
Theme Graphic

Jonesy's Great Code Archive

This is for me, not you. But I hope you find it useful none-the-less. Suggestions or general comments are appreciated.
Posted on Tuesday, August 25, 2009 at 7:07 AM

How to remove duplications from a temp table in MSSQL.

Here is an example of how to remove duplicates from a temporary table in MSSQL.

create table marxBrothers (
    ident int IDENTITY,
    Name varchar(32)
)
go
insert marxBrothers (Name)
    select 'Groucho Marx' UNION ALL
    select 'Harpo Marx' UNION ALL
    select 'Chico Marx' UNION ALL
    select 'Groucho Marx' UNION ALL
    select 'Harpo Marx' UNION ALL
    select 'Chico Marx' UNION ALL
    select 'Zeppo Marx' UNION ALL
    select 'Gummo Marx' UNION ALL
    select 'Zeppo Marx'
    
select * from marxBrothers
delete marxBrothers
from marxBrothers,
    (
        select min(ident) as minIdent, name
        from marxBrothers m
        group by name
        having count(1) > 1
    ) as derived
where marxBrothers.name = derived.name
-- This 'and' makes sure that one of the duplications is not deleted, 
-- remove it if you do not want one copy of the duplication to remain.
and ident > minIdent

select * from marxBrothers...

 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.