DECLARE @tempId NVARCHAR(Max), @tempIDD uniqueidentifier WHILE EXISTS ( SELECT UserId FROM Users Group By UserId having (count(*))>1 ) BEGIN SELECT TOP 1 @tempId = UserId FROM (SELECT UserId FROM Users Group By UserId having (count(*))>1 ) #cc Select Top 1 @tempIDD=Id FROM Users where UserId=@tempId DELETE FROM Users WHERE [id] = @tempIDD END
上面这种方式,效率比较低。改进后的方式如下:
Delete From Users WHERE ID in (SELECT min(ID) FROM Users Group By UserId having (count(*))>1 )