MSSQL T-SQL 通过存储过程删除重复数据


  ##重新来一遍
 create table xiutaoX200a(
id int not null primary key identity(1,1),
秀套编号 nvarchar(max),
所属车型  nvarchar(max),
车型编号  nvarchar(max),
车型说明  nvarchar(max),
产品类别  nvarchar(max),
拆装难度  nvarchar(max),
座位数量  nvarchar(max),
参考年份  nvarchar(max),
车型区分相片  nvarchar(max),
车型参数  nvarchar(max),
拼接示意图片  nvarchar(max),
实物品相片  nvarchar(max),
a360脚垫单片拼接图  nvarchar(max),
汽车座椅尺寸  nvarchar(max),
当前网页URL  nvarchar(max),
当前网页标题  nvarchar(max)
)

 -- 做个备份
 select * into xiutaoX200a2 from xiutaoX200a


 --批量处理重复数据

 -- select  * from xiutaoX200a 

 
--测试案例,给表插入数据
 
-- select * from xiutaoX200a
--判断临时表是否存在 如果存在则删除临时表
if exists(select 1 from tempdb..sysobjects where id=object_id('tempdb..#t_m'))
begin
 drop table #t_m --删除临时表
end
--将数据插入临时表
select * into #t_m from xiutaoX200a2
--开始循环表数据
 
 declare @tmid int ; -- 创建一个临时变量
 declare @url varchar(max)
 declare @groupCount int ;
 declare @delCount int; 
 set @delCount=0;
While (exists ( select 1 from #t_m))
BEGIN
select top 1 @tmid =id ,@url= 当前网页URL  from #t_m --拿出一条数据复制在临时变量里面, 用于待会删除该数据使用
--
 /*
 好了 在这里使用 @tmid 来操作 该条数据吧
 */
--
-- 使用URL 来获取数据条数
declare @existsCount int ;
select   @existsCount= count(0)  from xiutaoX200a2 where  当前网页URL in (
select 当前网页URL from xiutaoX200a2  where 当前网页URL =@url group by 当前网页URL  having ( count(当前网页URL)>1 ) ) 
if(@existsCount>1)
begin
    delete  xiutaoX200a2 where id in (
                        select   top (@existsCount-1 ) id from xiutaoX200a2 where  当前网页URL in (
select 当前网页URL from xiutaoX200a2  where 当前网页URL =@url group by 当前网页URL  having ( count(当前网页URL)>1 ) ) 
                                        )
                                        set @delCount=@delCount+1; 
end

/*

*/
DELETE #t_m WHERE ID=@tmid; --删除一条临时表的数据
END
if exists(select 1 from tempdb..sysobjects where id=object_id('tempdb..#t_m'))
begin
 drop table #t_m --操作结束后删除临时表
end    

 select @delCount