Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete duplicate (repetitive) records, rows from table without id [duplicate]

I have studied on it and the most practical way I found was to create a procedure. The procedure
adds an id, delete duplicate rows, and finally adds an id column to newly formed table. I wonder, there must be an easier way. Here's the code, it works...

--my table

create table dublicateTable
(
name varchar(30)
)

--duplicatedly inserted rows

insert into dublicateTable values('Kerem')
insert into dublicateTable values('Taner')
insert into dublicateTable values('Mehmet')
insert into dublicateTable values('Serhat')

--first situation

select * from dublicateTable


name
-----
Kerem
Kerem
Kerem
Taner
Taner
Mehmet
Mehmet
Mehmet
Mehmet
Serhat
Serhat
Serhat

--dynamicaly formed sql code procedure

USE [myDataBase]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[usp_delete_duplicate]
as
declare 
@add_id_text nvarchar(50),
@delete_id_text nvarchar(50),
@command_text nvarchar(100)
begin
set @add_id_text='alter table dbo.dublicateTable add id int identity(1,1)'
set @command_text='delete from dbo.dublicateTable where id not in(select min(id) from dbo.dublicateTable group by name)'
set @delete_id_text='alter table dbo.dublicateTable drop column id'
exec sp_executesql @add_id_text
exec sp_executesql @command_text
exec sp_executesql @delete_id_text
exec sp_executesql @add_id_text
end

--final situation.it works..

exec usp_delete_duplicate


select id,name from dublicateTable


id      name
---     ----
 1      Kerem
 2      Taner
 3      Mehmet
 4      Serhat
like image 947
kadir bozan Avatar asked Jul 02 '13 17:07

kadir bozan


People also ask

How do you delete duplicate records in the same table?

To delete the duplicate rows from the table in SQL Server, you follow these steps: Find duplicate rows using GROUP BY clause or ROW_NUMBER() function. Use DELETE statement to remove the duplicate rows.

Can you delete duplicate rows in a table without using a temporary table?

You could do this without a problem by using a common table expression (CTE), you don't need to use any temporary tables at all. Just be careful if the delete is going against a high traffic table. Deleting large amounts of data can cause locking and blocking, also the tran log will be hit.


1 Answers

A CTE can make it much simpler to write.

;with cte as (
    select
        name,
        row_number() over (partition by name order by name) row
    from
        dublicateTable
)
delete from cte where row > 1
like image 159
JC Ford Avatar answered Nov 14 '22 23:11

JC Ford