sql散记
来源:互联网 发布:js控制css3动画触发 编辑:程序博客网 时间:2024/04/29 23:05
关于删除重复行(保留一行)
假设目标表 person为:
1,使用临时表
method 1
select distinct * into #t from person -- 把所有不重复的行填充到临时表#t
truncate table person --删除源表
insert person select * from #t --复制临时表到源表
drop table #t -- 删除临时表
PS:该方法存在局限性,当数据库的表中存在image,text类型字段时会报错,提示该类型字段无法进行distinct操作
method 2
select *,count(*) as count into #t from person
group by name,age,department
having count(*)>1 --复制重复的行(单条记录)到临时表#t
delete from person where exists(
select * from #t b where person.age=b.age and
person.department=b.department and person.Name=b.Name) -- 把源表有重复的行都删掉
insert into person( age,Name,department)
select age,Name,department from #t --把重复的行(单条记录)插入源表
drop table #t
method 3 : 带索引的临时表
select * into #t from person where 1<>1--复制表结构
create unique index myindex on #t(Name,age,department) with ignore_dup_key --设置索引,忽略重复的列
insert #t select * from person --
truncate table person
insert into person select * from #t
truncate table #t
2 使用游标
declare @name as nvarchar(10),@icount as int=0declare person_cursor cursorfor select name,count(*) from person group by name having count(*)>1 -- 这里只筛选name列做个说明open person_cursorfetch next from person_cursor into @name,@icountwhile @@FETCH_STATUS=0begindelete top(@icount-1) from person where name=@name --(删除icount-1条记录,保留一条)fetch next from person_cursor into @name,@icountendclose person_cursordeallocate person_cursor
-- PS:可以使用 'SET @ICOUNT=@ICOUNT-1 SET ROWCOUNT @ICOUNT' 代替DELETE中的TOP,但不建议这么做.
-- 语法:set rowcountnumber | @number
--参数:整数
--作用 :停止指令之前要处理的行数
--set rowcount 0 关闭该选项,即处理所有行
- sql散记
- 散记
- 散记
- 散记
- 散记
- 散记
- 散记
- 散记
- 【学习散记7--SQL语句的处理】
- 学习散记7--SQL语句的处理
- 【学习散记12之---SQL Server 恢复模式】
- 学习散记12之---SQL Server 恢复模式
- 台北散记
- 软件散记
- js散记
- 散记-static
- 散记-extern
- 散记-const
- java中的后缀运算符
- js对象宽高图文解释
- 二分查找Binary Search
- AJax技术
- Yii-编程- 常用调用收集
- sql散记
- 2012年的就业形势 - 献给2012已毕业和2012即将毕业的学子(漫步人生路)
- struts2提供的校验器
- 设置修改CentOS系统时区
- Ubuntu/Linux下7款轻量级编辑器推荐
- MFC中用CFile读取和写入文件
- Rails link_to 详解
- ubuntu安装JDK时候出./install.sfx.2354: not found问题的解决方法
- shell脚本编程中for while until三种循环的使用方法