需求如下:
需要整个库的所有表做一次瘦身工作。每个表仅保留前200行,也就是要删除前200行后的记录行。我的想法如下,写一个游标,获取该库中所有表。在循环中依次对每个表减肥。问题一:我的这个方案是否可行?
问题二:是否有更合理可替代方案?
问题三:这个循环体怎么写?也就是怎么实现每个表保留前200行,删除多余行?谢谢解答、建议及顶帖的坛友。

解决方案 »

  1.   

    delete from table1 where colum1 not in (select top 200 colum1 from table1)
      

  2.   

    比如表a.select id1=identity(int,1,1) , * into #a from adelete * from #a where id1 > 200truncate table ainsert into a select col1,col2..... from #a
      

  3.   

    没有Identity类型字段。
    采用的是复合主键,由多个字段构成的。而且构成字段的数目不固定。
    如果是单字段主键,很多事情不会那么复杂了:)不过老乌龟的方法可以借鉴。select top 200 * into #a from a
    truncate table a
    insert into a select * from #a
      

  4.   

    --用CheckSum(*)
    delete 表名 where checksum(*) not in (select top 200 checksum(*) from 表名)
    --前提:表中字段不能含有 text、ntext、image、cursor 类型。
      

  5.   

    CheckSum(*)能唯一确定一行吗?如果可以确定,那倒是少打好几个字,呵呵
      

  6.   

    如果表中不存在text、ntext、image、cursor ,可以使用。只要表中存在关键字,可以确保唯一。
      

  7.   

    delete from tablename where 主健 not in (select top 200 主健 from tablename)
      

  8.   

    楼上的大哥,主键由多个字段组成的,用 where 主健 not in (select top 200 主健 from tablename) 这种写法是要出人命的:)
      

  9.   

    不论表中关键字是几个字段,只要存在关键字,确保表中不存在完全相同的记录,且没有text、ntext、image、cursor 类型的字段,都可以使用CheckSum(*)。
    delete 表名 where checksum(*) not in (select top 200 checksum(*) from 表名)例子:select top 1000 identity(int,1,1) as ID
    into #tp
    from syscolumns c1, syscolumns c2
    select * from #tpdelete #tp where checksum(*) not in (select top 200 checksum(*) from #tp)select * from #tpdrop table #tp
      

  10.   

    大家来接分,今天接贴
    http://community.csdn.net/Expert/topic/5128/5128233.xml?temp=.6066248
    http://community.csdn.net/Expert/topic/5128/5128222.xml?temp=.7657587
      

  11.   

    accp_fangjian(淡雅知己)
    提醒楼主一下,取前200条记录倒是容易,只是你要想好表之间的引用关系,否则会有很麻烦的隐患的!
    ============================
    谢谢提醒,其实我只要有几行数据样例就够了,我中是想参考这个库的表结构,因为没有数据字典,所以要用样例数据行来确定。