更正SQL Server数据库中的重复记录

时间:2016-04-03 19:18:51

标签: sql sql-server sql-server-2008 stored-procedures

我有一个包含许多记录的表,其中有一个nic列,它应具有唯一值。但它包含一些污垢,意味着那里有一些重复的值。

用户一样
id = 567 has nic = '786-786' 

以及

id = 897 has nic = '786-786'.

我想编写一个存储过程,应该删除那些副本并在最后添加1,如

id = 567 , nic= '786-786'
id = 788 , nic = '786-786-1'
id = 2344, nic = '786-786-2'

有可能吗?

2 个答案:

答案 0 :(得分:0)

使用窗口函数/解析函数,例如

Row_number() over (partition by Nic, order by ID)

SQL Fiddle 有点像...

UPDATE B
SET B.Nic = C.NewNic
FROM Foo B
INNER JOIN (SELECT ID, NIC + '-'  + cast(Row_number() 
over (partition by NIC order by ID ) as varchar(20)) as newNic
FROM FOo) C
 on C.ID = B.ID

这会给你

id = 567 , nic= '786-786-1'
id = 788 , nic = '786-786-2'
id = 2344, nic = '786-786-3'

你总是可以做一个case语句,当row为1然后不显示,如果必须离开第一个没有-1,则减去1

SQL Fiddle getting rid of the -1 for first record...

UPDATE B
SET B.Nic = Case WHEN C.RN = 1 then B.Nic Else B.Nic+ '-'+cast((RN-1) as varchar(20)) end
FROM Foo B
INNER JOIN (SELECT ID, NIC, cast(Row_number() 
over (partition by NIC order by ID ) as varchar(20)) as RN
FROM FOo) C
 on C.ID = B.ID

导致:

ID  NIC
567 786-786
897 786-786-1

SQL Fiddle显示多个网站

ID  NIC
567 786-786
600 786-786-1
897 786-786-2
10  786-787
12  786-787-1
900 786-787-2

答案 1 :(得分:0)

for tsql

您可以通过简单的更新来完成此操作,请尝试以下查询:

select id, nic, rank() over (partition by nic order by id)
from your_table as t1
where exists(select 1 from your_table where nic = t1.nic and id <> t1.id)

您可以构建更新查询,或将更新字符串作为此选择的字段返回。阅读rank()