批量删除表中的重复数据,仅保留一条不重复数据.

  我们在SQL数据中,经常遇到一个表中有许多的重复数据,如何才能删除那些重复的数据,仅保留一条不重复的数据呢?

一般情况我们会分四步来处理:

 1 --原来的表结构:
 2 create table dict_xh
 3 (
 4     id int not null,
 5     xh varchar(50) not null 
 6 )
 7 
 8 --1.新建一张临时表xinghao
 9 create table xinghao
10 (
11     id int not null,
12     xh varchar(50) not null 
13 )
14 --2.设置正确的索引,忽略重复数据。
15     GO
16     -- CSDN标准写法
17     IF EXISTS (SELECT name from sys.indexes
18                WHERE name = N'Ad_xh_Unique') 
19        DROP INDEX Ad_xh_Unique ON xinghao; 
20     GO
21     -- 在表xinghao列xh上 创建一个唯一索引,忽略重复数据
22     CREATE UNIQUE INDEX Ad_xh_Unique 
23        ON xinghao(xh) WITH IGNORE_DUP_KEY ON [PRIMARY]; 
24     GO
25 
26 --3.将带有重复数据的表复制到该临时表中
27     Go
28     insert into xinghao select * from dict_xh
29 --4.删除原重复表的所有数据,将临时表中的数据复制到原重复表,删除临时表
30     GO
31     --删除原表中数据
32     delete from dict_xh
33     --复制临时表中的数据到原表
34     insert into dict_xh select * from xinghao
35     --删除临时表
36     drop table xinghao
作者:枫上善若水
出处:http://www.cnblogs.com/xilipu31/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!
原文地址:https://www.cnblogs.com/xilipu31/p/2799025.html