5 de octubre de 2011

Elimina registros duplicados en una tabla

Drop table tmpT1
Create table tmpT1 (col1 int,col2 int)
   
Insert into tmpT1 values (1,1)
Insert into tmpT1 values (1,2)
Insert into tmpT1 values (1,1) --duplicada
Insert into tmpT1 values (1,4)
Insert into tmpT1 values (1,5)

drop table tmpT2
Select * into tmpT2 from tmpT1

truncate table tmpT2

Declare @Col1 int,@Col2 int
Declare CursorA CURSOR forward_only FOR
Select * from tmpT1
OPEN CursorA
FETCH NEXT FROM CursorA
INTO @Col1,@Col2
WHILE @@FETCH_STATUS = 0
BEGIN
    If not exists(Select * from tmpT2 where Col1=@Col1 and Col2=@Col2)
    Insert into tmpt2 values (@Col1,@Col2)   
   
    FETCH NEXT FROM CursorA
     INTO @Col1,@Col2
END
CLOSE CursorA
DEALLOCATE CursorA

Select * from tmpT1
Select * from tmpT2

No hay comentarios:

Publicar un comentario