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

数据库 SQL Server
sql 删除重复记录没有大小关系时,重复值将如何处理呢? 下文就将为您介绍sql删除重复记录没有大小关系时重复值的处理方法,供您参考,希望对您有所启迪。

sql 删除重复记录没有大小关系时,重复值将如何处理呢? 下文就将为您介绍sql删除重复记录没有大小关系时重复值的处理方法,供您参考,希望对您有所启迪。

--> --> (roy)生成

if not object_id(tempdb..#t) is null
    drop table #t
go
create table #t([num] int,[name] nvarchar(1))
insert #t
select 1,na union all
select 1,na union all
select 1,na union all
select 2,nb union all
select 2,nb
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           a
2           b

(2 行受影响)#p#
*/

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

alter table #t add id int identity--新增标识列
go
delete a from  #t a where  exists(select 1 from #t where num=a.num and name=a.name and id>a.id)--只保留一条记录
go
alter table #t drop column id--删除标识列--查看结果
select * from #t

/*
num         name
----------- ----
1           a
2           b

(2 行受影响)

*/

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

declare roy_cursor cursor local for#p#
select count(1)-1,num,name from #t group by num,name having count(1)>1
declare @con int,@num int,@name nvarchar(1)
open roy_cursor
fetch next from roy_cursor into @con,@num,@name
while @@fetch_status=0
begin
    set rowcount @con;
    delete #t where num=@num and name=@name
    set rowcount 0;
    fetch next from roy_cursor into @con,@num,@name
end
close roy_cursor
deallocate roy_cursor--查看结果
select * from #t
/*
num         name
----------- ----
1           a
2           b

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

declare @max integer,@id integer
declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) > 1
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
delete from 表名 where 主字段 = @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0//使用函数

select distinct * into #tmp from tablename
drop table tablename
select * into tablename from #tmp
drop table #tmp

本文转载自【web优化网】新闻中心:http://www.web-youhua.com/html/web-youhua-198601001.html

责任编辑:段燃 来源: WEB优化网
相关推荐

2010-10-13 17:07:46

MySQL删除重复记录

2010-10-13 17:13:17

MySQL重复记录

2010-09-25 16:17:25

SQL语句

2010-11-23 14:26:02

MySQL删除重复记录

2010-10-27 16:49:23

Oracle删除重复记

2010-09-03 09:49:39

SQL删除

2010-09-28 15:40:51

SQL删除重复记录

2010-09-28 15:46:22

SQL删除重复记录

2010-11-25 15:43:02

MYSQL查询重复记录

2010-07-26 17:00:11

SQL Server查

2011-05-24 10:04:39

Oracle重复记录

2010-10-27 16:56:05

Oracle重复记录

2010-09-30 10:29:56

DB2删除重复记录

2011-03-04 17:30:42

Oracle数据库

2010-07-02 13:50:11

SQL Server数

2010-11-15 14:42:03

Oracle查询重复记

2011-03-21 17:25:08

SQL Server数重复记录

2010-04-13 10:23:40

Oracle数据库

2011-05-17 11:23:02

Oracle数据库

2010-09-01 16:47:18

SQL删除
点赞
收藏

51CTO技术栈公众号