SQL Server如何删除重复记录

海外服务器 (539) 2015-11-11 09:42:34

—、建立一张具有相同结构的临时表

CREATE TABLE Products_temp (
ProductID int,
ProductName nvarchar (40),
Unit char(2),
UnitPrice money
)

 

二、为该表加上索引,并使其忽略重复的值

方法是在企业管理器中找到上面建立的临时表Products _temp,单击鼠标右键,选择所有任务,选择管理索引,选择新建。如图2所示。

按照图中圈出来的地方设置索引选项。

三、拷贝产品信息到临时表

insert into Products_temp Select * from Products

 

此时SQL Server会返回如下提示:

服务器:消息 3604,级别 16,状态 1,行 1

已忽略重复的键。

它表明在产品信息临时表Products_temp中不会有重复的行出现。

四、将新的数据导入原表

将原产品信息表Products清空,并将临时表Products_temp中数据导入,最后删除临时表Products_temp。

delete Products
insert into Products select * from Products_temp
drop table Products_temp

 

这样就完成了对表中重复记录的删除。无论表有多大,它的执行速度都是相当快的,而且因为几乎不用写语句,所以它也是很安全的。

THE END