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

时间:2013-07-02 17:07:35

标签: sql sql-server database sql-server-2008 tsql

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

- 我的桌子

create table dublicateTable
(
name varchar(30)
)

- 重复插入的行

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

- 第一种情况

select * from dublicateTable


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

- 动态形成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

- 最终的情况。工作..

exec usp_delete_duplicate


select id,name from dublicateTable


id      name
---     ----
 1      Kerem
 2      Taner
 3      Mehmet
 4      Serhat

1 个答案:

答案 0 :(得分:3)

CTE可以使编写更加简单。

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