sql server 批量更新某重复字段,并保留一条

sql server 批量更新某重复字段,并保留一条

1.前提:假设sysuer表中telephone有重复,现在想把重复的更新成以8888+6位随机数,同时保留重复记录中最小id的一条。
2.具体步骤如下:
2.1找出重复的数据,并写到临时表aa,sql如下:
select * into aa from (select id ,telephone FROM sysuser as a
WHERE NOT EXISTS (
SELECT 1 FROM
(select telephone,MIN(id) AS id from sysuser group by telephone having count() >1) b
WHERE a.id=b.id
)
and EXISTS (SELECT 1 FROM
(select telephone from sysuser group by telephone having count(
) >1) c
WHERE a.telephone=c.telephone)) t
2.2将aa表中telephone字段生成随机数,sql如下:
declare @min_id int
set @min_id=(select MIN(Id) from aa)
while @min_id>0
begin
update aa set telephone=CONCAT(‘8888’,100000+cast( floor(rand()*999999) as int)) where Id=@min_id

select @min_id=(select MIN(Id) from aa where Id>@min_id)
end
2.3更新目标表sysuser中telephone字段,sql如下:
update sysuser set telephone=(select telephone from aa where sysuser.id=aa.id) where sysuser.id in (select id from aa)
2.4删除临时表aa

你可能感兴趣的:(sql,server)