6

我研究过它,我发现最实用的方法是创建一个程序。该过程
添加一个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
4

1 回答 1

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
于 2013-07-02T17:14:36.753 回答