Removing duplicated values from a table / Removendo valores duplicados de uma tabela

In T-SQL you may use "insert" to remove duplicates. What you must do is create another work table with the IGNORE_DUP_KEY option set.

So you copy the data from one table to the other. Drop the original table and rename the work table to your original table name and that's it. You will have a plain, clean, non duplicated records table. Something like:

CREATE TABLE tableCleanDup
(idfield int, field1 varchar(30), field2 varchar(30))
CREATE UNIQUE INDEX removeduplicates ON tableCleanDup (field1,field2) WITH IGNORE_DUP_KEY
GO
INSERT tableCleanDup SELECT * FROM tableOriginal

It will return to you a message "duplicate key was ignored" but that is fine. The tableCleanDup will have the records from tableOriginal but without duplicates.

p.s.: Thanks to Ken Henderson for this T-SQL advice.

Versão em Português

Em T-SQL você pode usar o "insert" para remover valores diplicados em uma tabela. O que vc precisa fazer é criar uma tabela de trabalho com o parâmetro IGNORE_DUP_KEY.

Então vc copia os dados de uma tabela para outra. Deleta a tabela original e depois renomeia a tabela de trabalho com o nome da tabela original e é isso. Vc terá uma nova tabela limpa. sem linhas duplicadas. O código é algo como:

CREATE TABLE tableCleanDup
(idfield int, field1 varchar(30), field2 varchar(30))
CREATE UNIQUE INDEX removeduplicates ON tableCleanDup (field1,field2) WITH IGNORE_DUP_KEY
GO
INSERT tableCleanDup SELECT * FROM tableOriginal

O insert acima ira retornar uma mensagem "duplicate key was ignored" mas esta tudo certo. A tabela tableCleanDup irá possuir todos os records da tabela tableOriginal mas sem os duplicados.

p.s.: Obrigado ao Ken Henderson por essa dica.

Comments

Consumed By Feed-Squirrel.com