程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> 更多數據庫知識 >> SQL Server2008中刪除重復記錄的方法分享

SQL Server2008中刪除重復記錄的方法分享

編輯:更多數據庫知識

現在讓我們來看在SQL SERVER 2008中如何刪除這些記錄, 首先,可以模擬造一些簡單重復記錄:
復制代碼 代碼如下:
Create Table dbo.Employee (
[Id] int Primary KEY ,
[Name] varchar(50),
[Age] int,
[Sex] bit default 1
)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(1,'James',25,default)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(2,'James',25,default)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(3,'James',25,default)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(4,'Lisa',24,0)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(5,'Lisa',24,0)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(6,'Lisa',24,0)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(7,'Mirsa',23,0)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(8,'Mirsa',23,0)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(9,'Mirsa',23,0)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(10,'John',26,default)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(11,'Abraham',28,default)
Insert Into Employee ([Id] , [Name] , [Age] , [Sex] ) Values(12,'Lincoln',30,default)

OK,首先我們使用最常見的方法:

Delete From Employee Where Name in (select NameFrom Employee Group By Name Having Count(Name)>1);
接著使用RowNumber():

Delete T From( Select Row_Number() Over(Partition By [Name] Order By (SELECT 0)) As RowNumber,* From Employee) TWhere T.RowNumber > 1;

還可以使用CTE (Common Table Expressions):

復制代碼 代碼如下:
With Dups as
(
select ROW_NUMBER() Over(Partition by [Name] Order by (SELECT 0)) as rn
FROM Employee
)
Delete From Dups
Where rn>1;

再加上RANK()的CTE:
復制代碼 代碼如下:
WITH Dups As
(
Select [ID],[Name],[Age],[Sex]
, ROW_NUMBER() OVER(Partition By [Name] Order By (SELECT 0)) AS rn
,RANK() OVER(Partition By [Name] Order By (SELECT 0)) AS rnk
FROM Employee
)
DELETE FROM Dups
WHERE rn<>rnk;

下面是這四個T-SQL查詢的執行計劃:

ExecutionPlan1

你可以看到沒有用CTE的方法開銷最大, 主要是在Table Spool, 這裡開銷了44%, Table Spool 是一個物理運算符。

Table Spool 運算符掃描輸入,並將各行的一個副本放入隱藏的假脫機表中,此表存儲在 tempdb 數據庫中並且僅在查詢的生存期內存在。如果重繞該運算符(例如通過 Nested Loops 運算符重繞),但不需要任何重新綁定,則將使用假脫機數據,而不用重新掃描輸入。
注意上面的方法只是在重復記錄比較少的情況下, 如果重復記錄多. DELETE將會非常慢, 最好的方法是復制目標數據到另一個新表,刪除原來的表,重命名新表為原來的表. 或用臨時表, 這樣還可以減少數據庫事務日志. 看下面的T-SQL:
復制代碼 代碼如下:
WITH Dups As
(
Select [ID],[Name],[Age],[Sex]
, ROW_NUMBER() OVER(Partition By [ID] Order By (SELECT 0)) AS rn
FROM Employee
)
Select [ID],[Name],[Age],[Sex]
INTO dbo.EmployeeDupsTmp
FROM Dups
WHERE rn=1
DROP TABLE dbo.Employee;
EXEC sp_rename 'dbo.EmployeeDupsTmp','Employee'

希望這篇POST對您開發有幫助.作者:Petter Liu

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved