sql 删除重复记录没有大小关系时,处理重复值

来源:http://www.guanqinbiaoye.com 作者:计算机数据 人气:193 发布时间:2020-03-01
摘要:sql 删除重复记录没有大小关系时,处理重复值 -- -- (roy)生成 if not object_id('tempdb..#t') is null drop table #tgocreate table#t([num] int,[name] nvarchar(1))insert #tselect 1,n'a' unionallselect 1,n'a' union allselect 1

sql 删除重复记录没有大小关系时,处理重复值

-- -- (roy)生成

if not object_id('tempdb..#t') is null drop table #tgocreate table #t([num] int,[name] nvarchar(1))insert #tselect 1,n'a' union allselect 1,n'a' union allselect 1,n'a' union allselect 2,n'b' union allselect 2,n'b'go

方法1:

if object_id('tempdb..#') is not null drop table #select distinct * into # from #t--排除重复记录结果集生成临时表#

truncate table #t--清空表

insert #t select * from # --把临时表#插入到表#t中

威尼斯网站,--查看结果select * from #t

/*num name----------- ----1 a2 b

(2 行受影响)*/

--重新执行测试数据后用方法2方法2:

alter table #t add id int identity--新增标识列godelete a from #t a where exists(select 1 from #t where num=a.num and name=a.name and ida.id)--只保留一条记录goalter table #t drop column id--删除标识列

--查看结果select * from #t

/*num name----------- ----1 a2 b

(2 行受影响)

*威尼斯游戏网站,/

--重新执行测试数据后用方法3方法3:

declare roy_cursor cursor local forselect count(1)-1,num,name from #t group by num,name having count(1)1declare @con int,@num int,@name nvarchar(1)open roy_cursorfetch next from roy_cursor into @con,@num,@namewhile @@fetch_status=0begin set rowcount @con; delete #t where num=@num and name=@name set rowcount 0; fetch next from roy_cursor into @con,@num,@nameendclose roy_cursordeallocate roy_cursor

--查看结果select * from #t/*num name----------- ----1 a2 b

(2 行受影响)*///利用存储过程

declare @max integer,@id integerdeclare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) 1open cur_rowsfetch cur_rows into @id,@maxwhile @@fetch_status=0beginselect @max = @max -1set rowcount @maxdelete from 表名 where 主字段 = @idfetch cur_rows into @id,@maxendclose cur_rowsset rowcount 0

//使用函数

select distinct * into #tmp from tablenamedrop table tablenameselect * into tablename from #tmpdrop table #tmp

本文由威尼斯游戏网站发布于计算机数据,转载请注明出处:sql 删除重复记录没有大小关系时,处理重复值

关键词:

最火资讯