首页 技术 正文
技术 2022年11月21日
0 收藏 389 点赞 3,724 浏览 1364 个字

本文介绍了Sql Server数据库中删除数据表中重复记录的方法。

[项目]
数据库中users表,包含u_name,u_pwd两个字段,其中u_name存在重复项,现在要实现把重复的项删除!
[分析]
1、生成一张临时表new_users,表结构与users表一样;
2、对users表按id做一个循环,每从users表中读出一个条记录,判断new_users中是否存在有相同的u_name,如果没有,则把它插入新表;如果已经有了相同的项,则忽略此条记录;
3、把users表改为其它的名称,把new_users表改名为users,实现我们的需要。
[程序]

declare @id int,@u_name varchar(50),@u_pwd varchar(50)
set @id=1
while @id<1000
begin
if exists (select u_name from users where u_id=@id)
begin
select @u_name=u_name,@u_pwd=u_pwd from users where u_id=@id --获取源数据
if not exists (select u_name from new_users where u_name=@u_name) -- 判断是否有重复的U-name项
begin
insert into new_users(u_name,u_pwd) values(@u_name,@u_pwd)
end
end
set @id=@id+1
end
select * from new_users

[方法二]

假设Users表中有相同的name项,id为主键标识字段。现在要求去掉Users中重复的name项。
1、把不重复的ID保存在一个tmp1表里面。
select min([id]) as [id] into tmp1 from Users group by [name]

2、从Users表中选取tmp1表中的id项,将相应id的数据写入表tmp2
select * into tmp2 from Users where [id] in( select [id] from tmp1)

3、把Users、tmp1两张表Drop掉
drop table Users
drop table tmp1

4、把tmp2表改名为User表
[注]如果没有主键标识id,可以增加一个标识字段,方法如下:
select identity(int,1,1) as autoID, * into tmp0 from Users
[情况三](脚本学堂 www.jbxue.com)
假设有一个User表,id为主键标识字段,但有一些完全重复的项。现在要求去掉Users中这些完全重复的项,只保留一条。
1、把不重复的数据保存在tmp1表中
select distinct * into tmp1 from Users

2、把Users表删除
drop table Users

3、把tmp1表中的数据导入到Users表
select * into Users from tmp1

4、把tmp1表删除
drop table tmp1

参考链接:

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919