如何从没有id的表中删除重复(重复)记录,行[duplicate]

时间:2022-10-21 22:25:59

This question already has an answer here:

这个问题在这里已有答案:

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...

我研究过它,我找到的最实用的方法是创建一个程序。该过程添加一个id,删除重复的行,最后将一个id列添加到新形成的表中。我想知道,必须有一个更简单的方法。这是代码,它的工作原理......

--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

--dynamicaly形成了sql代码程序

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

1 个解决方案

#1


3  

A CTE can make it much simpler to write.

CTE可以使编写更加简单。

;with cte as (
    select
        name,
        row_number() over (partition by name order by name) row
    from
        dublicateTable
)
delete from cte where row > 1

#1


3  

A CTE can make it much simpler to write.

CTE可以使编写更加简单。

;with cte as (
    select
        name,
        row_number() over (partition by name order by name) row
    from
        dublicateTable
)
delete from cte where row > 1