在对数据库操作的过程中难免会因为操作失误使数据库中的数据表中出现重复数据,下面我们要将这些数据重复数大于一的其他数据删除,只保留一条。
关于这个问题的处理方式网上一搜一大堆,但是以下两种方法貌似还没有,在此将代码贴出来期待大家指出其中的不足,我将非常感谢。
有如下几种方法可以解决
方法1 游标
DECLARE @DupCount INT,@Number NCHAR(10),@Name VARCHAR(20),@Address NVARCHAR(50)
DECLARE Cur CURSOR
READ_ONLY
FOR
SELECT COUNT(*) AS Total,Number,Name,[Address]
FROM [MyDataBase].[dbo].[MyTest]
GROUP BY Number,Name,[Address] HAVING(COUNT(*)>1)
OPEN Cur
FETCH NEXT FROM Cur INTO @DupCount,@Number,@Name,@Address
WHILE(@@FETCH_STATUS=0)
BEGIN
DELETE TOP(@DupCount-1) FROM
[MyDataBase].[dbo].[MyTest]
WHERE Number=@Number AND Name =@Name AND [Address]=@Address
FETCH NEXT FROM cur INTO @DupCount,@Number,@Name,@Address
END
CLOSE Cur
DEALLOCATE Cur
方法2 临时表,这种方法太暴力一般不推荐
SELECT * INTO #TEMPTABLE
FROM
(
SELECT * FROM [MyDataBase].[dbo].[MyTest]
UNION
SELECT * FROM [MyDataBase].[dbo].[MyTest]
) AS R
DROP TABLE [MyDataBase].[dbo].[MyTest]
SELECT * INTO [MyDataBase].[dbo].[MyTest]
FROM #TEMPTABLE
DROP TABLE #TEMPTABLE
.Net、SqlServer开发新手,学习ing