zoukankan      html  css  js  c++  java
  • 如何删除 SQL Server 表中的重复行

    第一种:有主键的重复行,就是说主键不重复,但是记录的内容重复
    比如人员表tab ,主键列id,身份证编号idcard
    当身份证重复的时候,保留最小id值的记录,其他删除
    delete a from tab a where exists(select 1 from tab where idcard = a.idcard and id < a.id)

    第二种:没有主键的重复行,这种重复的意思是两条记录完全重复,所有字段的值都一样,而且表因为设计失误没有主键
    这种可以有两种方式删除
    1. 加标示列
    alter table tab add id int identity(1,1) ,加上以后,这个情况就变成了第一种情况,删除语句同上

    2. 中间表,把重复数据导出来,删掉原表数据,再吧数据导回去
    --导出
    select a,b,c,d from tab into #tab group by a, b,c,d having count(1) > 1
    --删除
    delete a from tab t1 inner join #tab t2 on t1.a = t2.a and t1.b = t2.b and t1.c = t2.c and t1.d = t2.d
    --导回
    insert into tab select * from #tab

    这两种情况根据实际情况自行选用
  • 相关阅读:
    第0次作业
    第4次作业
    第3次作业
    第2次作业
    C#浮点数保留位数
    第0次作业
    软件工程第4次作业
    软件工程第3次作业
    软件工程第2次作业
    软件工程第1次作业
  • 原文地址:https://www.cnblogs.com/sdusrz/p/3936515.html
Copyright © 2011-2022 走看看