sqlserver如何将重复的数据删除掉
1、首先我们需要定义我们需要的变量,查询分析器输入以下语句/**定义变量**/declare @name nvarchar(50),@num int,@price float
2、第二步:这里需要用到row_number函数,这个从名字可以看出是一个获取表所在行的行号函墙绅褡孛数,这个挣窝酵聒函数只能用在查询,所以我们需要将其插入到一个临时表在查询分析器中输入以下语句,将查询到的类容插入到#temp表select name,price,ROW_NUMBER()over (order by name) as num into #temp from product
3、第三步:定义游标,并且取一行数据/**定义游标**/Declare c_quchong cursor forselect name,price,num from #tempopen c_quchongfetch next from c_quchong into @name,@price,@num
4、第四步:循环执行取重操作while @@FETCH_STATUS=0begin/**执行去飒劐土懿重**/delete from #temp where num<>@num and name=@namefetch next from c_quchong into @name,@price,@numend
5、第五步:关闭游标并删除close c_quchongdeallocate c_quchong
6、第六步:清空product表数据将去重后的数据插入到product表
7、第七步:删除临时表drop table #temp
8、第八步:完整sql脚本语句/**定义变量**/declare @name nvarchar猾诮沓靥(50),@num int,@price float/***表数据插入临时表***/se造婷用痃lect name,price,ROW_NUMBER()over (order by name) as num into #temp from product/**定义游标**/Declare c_quchong cursor forselect name,price,num from #tempopen c_quchongfetch next from c_quchong into @name,@price,@numwhile @@FETCH_STATUS=0begin/**执行去重**/delete from #temp where num<>@num and name=@namefetch next from c_quchong into @name,@price,@numendclose c_quchongdeallocate c_quchong/**清空product表数据将去重后的数据插入到product表**/delete from productinsert into productselect name,price from #temp/**删除临时表**/drop table #temp
9、第九步:运行脚本后查询所在表数据结构,以上为去重操作,可根据自己实际情况进行修改