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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With