删除表中存在多条相同记录的方法

根据向临时表导入数据,并为其添加一个列ID为索引。
然后再向这个临时表查找相同记录的一条最大索引插入别一个表UC_CARDTL_Temp_ForImport
再次,删除表UC_CARDTL_Temp_ForImport中的列ID
最后,删除原表,再更改名称为原来的表名
use hos


If Exists(Select 1 From tempdb.dbo.sysobjects where Name = '##temp_UC_CarDTL' And Xtype = 'U')
    
drop table ##temp_UC_CarDTL
go

Select Identity(int,1,1as ID,* into ##temp_UC_CarDTL From UC_CardTL
go

If Exists(Select 1 From sysobjects where Name = 'UC_CARDTL_Temp_ForImport' And Xtype = 'U')
    
drop table UC_CARDTL_Temp_ForImport
go

Select * into UC_CARDTL_Temp_ForImport From ##temp_UC_CarDTL Where ID
    
In
(
    
Select Max(ID) From ##temp_UC_CarDTL Where 1=1 Group By CarName,CarID,Class Having Count(*> 1
)

Alter Table [UC_CARDTL_Temp_ForImport] Drop Column [ID]
go
Drop Table UC_CARDTL
go
sp_rename 
'UC_CARDTL_Temp_ForImport','UC_CARDTL'

转载请注明出处[http://samlin.cnblogs.com/

欢迎关注本人公众号:

作者赞赏
原文地址:https://www.cnblogs.com/samlin/p/1049146.html