如题,众所周知,可以用delete top n from tablename来删除表中前n个记录.现在我想要保留前n个(如10000)个记录,该如何处理?
表里有一个自增字段ID,它可能不是从1开始的.
是否先统计出有多少个字段,如果大于10000,则删除掉前面n-10000个记录,否则就什么事都不干.
请惠赐sql语句.谢谢

解决方案 »

  1.   

    delete tablename
    where id not in (select top 10000 id from tablename)
      

  2.   

    delete from tb where
    not exists(select top(10000)* from tb order by id)
    --试试这样行不,操作前先备份
      

  3.   

    id如果连续不缺号delete tablename
    where id > 10000
      

  4.   

    ;with f as
    (
    select id=row_number()over(order by id),* from tb
    )
    delete from f where id>10000
      

  5.   

    如果是删除掉除前10000条记录以外的其他记录,则可以:
    delete from tb where id>(select max(id) from(select top 10000 id from tb order by id)t)
      

  6.   

    我的那个不行,不能用not exists 
    那就用一楼的吧 not in
      

  7.   

    delete tablename where id not in (select top 10000 id from tablename)