精确查找可以插入重复记录的表,解决记录重复的问题
本文介绍处理重复数据的处理方法。
1.找出可以插入重复数据的表
use [你要处理的数据库]
select id,name from sysobjects where id in(
SELECT object_id FROM sys.indexes where object_id not in(
SELECT object_id FROM sys.indexes where is_unique=1 or is_primary_key=1 or is_unique_constraint=1)
) and xtype=’U’ order by name
再次过滤出哪些表存放有数据
SELECT object_name (i.id) TableName,
rows as RowCnt
FROM sysindexes i
INNER JOIN sysObjects o
ON (o.id = i.id AND o.xType = ‘U’)
WHERE indid < 2 and RowCnt>0 and i.id in(
select id from sysobjects where id in(
SELECT object_id FROM sys.indexes where object_id not in(
SELECT object_id FROM sys.indexes where is_unique=1 or is_primary_key=1 or is_unique_constraint=1)
) and xtype=’U’
)
ORDER BY RowCnt desc
2.处理重复数据的表,使相同记录只留一条
案例处理:重复数据处理测试.dbo.UA_Log_Ex 表有记录 520714条
去重查询方法:
USE [重复数据处理测试]
GO
SELECT
,
,
,
,
,
,
,
,
,
FROM 重复数据处理测试.dbo.UA_Log_Ex
group by
,
,
,
,
,
,
,
,
,
把所有字段用group by 就能过滤出唯一的记录
看处理后,记录数量减半,数量为260357条
把过滤后的记录插入一张临时表重复数据处理测试.dbo.TempTable,这个表会自动生成
USE [重复数据处理测试]
GO
SELECT
,
,
,
,
,
,
,
,
,
into 重复数据处理测试.dbo.TempTable
FROM 重复数据处理测试.dbo.UA_Log_Ex
group by
,
,
,
,
,
,
,
,
,
结果如下 :
最后一步,把原表数据清空,把重复数据处理测试.dbo.TempTable表数据搬回来
delete FROM [重复数据处理测试].. –删除原表数据
把数据从重复数据处理测试.dbo.TempTable表数据搬回来
insert into [重复数据处理测试]..
SELECT
,
,
,
,
,
,
,
,
,
FROM [重复数据处理测试]..
查看结果:
到此就处理结束了
总结
过滤重复记录查询用 group by 所有字段
把过滤结果插入新临时表 into Temptable
清除原表数据 delete from table
把临时表数据搬回原始表,用 insert into 原表
页:
[1]