現在讓我們來看在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):
復制代碼 代碼如下:下面是這四個T-SQL查詢的執行計劃:
你可以看到沒有用CTE的方法開銷最大, 主要是在Table Spool, 這裡開銷了44%, Table Spool 是一個物理運算符。
Table Spool 運算符掃描輸入,並將各行的一個副本放入隱藏的假脫機表中,此表存儲在 tempdb 數據庫中並且僅在查詢的生存期內存在。如果重繞該運算符(例如通過 Nested Loops 運算符重繞),但不需要任何重新綁定,則將使用假脫機數據,而不用重新掃描輸入。希望這篇POST對您開發有幫助.作者:Petter Liu