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

SQL Server2008中刪除反復記載的辦法分享

編輯:MSSQL2008

SQL Server2008中刪除反復記載的辦法分享。本站提示廣大學習愛好者:(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