Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Enterprise
Expertise: Advanced
Apr 22, 2002

Delete Duplicate Rows from a Table Using the Cursor


This is an advanced solution to delete duplicate Rows from a table using the cursor:
 
create table DupTable (
    Field1 varchar(20)
)
go
insert DupTable (Field1)
    select 'A11111111' UNION ALL
    select 'B22222222' UNION ALL
    select 'C33333333' UNION ALL
    select 'C33333333' UNION ALL
    select 'C33333333' UNION ALL
    select 'A11111111' UNION ALL
    select 'B22222222' UNION ALL
    select 'A11111111'

declare @sql varchar(255),
        @name varchar(32),
        @count int

declare MyCursor insensitive cursor for
select Field1, (count(1)-1) ExcssCount from DupTable
 group by Field1
 having count(1) > 1

open MyCursor
fetch next from MyCursor into @name,@count
while @@fetch_status = 0
begin
    select @sql =
    'set rowcount ' + convert(varchar(9), @count) + '
    delete DupTable where field1 = "' + @name + '"'

    exec (@sql)
    print @sql
    fetch next from MyCursor into @name, @count

end-- while fetch
close MyCursor
deallocate MyCursor
set rowcount 0
select * from DupTable

drop table DupTable
NageswaraRao Kurra
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date