【问题标题】:How To Set Limit Table Row SQL?如何设置限制表行SQL?
【发布时间】:2017-03-27 01:48:44
【问题描述】:

如何在 SQL Server 中设置限制表行数?

我想将我的表格行数限制为 100 行。

所以当表格有超过 100 行时,我想删除第一行然后将新行添加到最后一行 (100)。

我该怎么做?

【问题讨论】:

    标签: sql-server sql-server-2005


    【解决方案1】:

    我可以向你保证的一件事..

    1. 创建一个触发器,如果​​ > 100 则删除第一条记录。

    请参阅 here 作为您的指南。

    【讨论】:

      【解决方案2】:

      我认为你需要做两件事 i) 创建触发器

      declare @MaxRowLimit int=5
      declare @t table(col1 int)
      insert into @t values(1),(2),(3),(4),(5)
      
      insert into @t VALUES(12)
      
      ;With CTE as
      (
      
      
      select top (@MaxRowLimit) col1 
      
      from @t t1
      order by t1.col1 desc
      )
      ,CTE1 as(
      select * from @t t
      where not exists
      (select  col1 
      
      from cte t1 where t.col1=t1.col1
      )
      )
      delete from cte1
      select * from @t
      

      ii) 如果是大容量插入,则在大容量插入之前进行操作。 比如如果批量插入计数大于 100,则排序并保留最后 100 行并删除其余行。

      【讨论】:

        猜你喜欢
        • 2011-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        相关资源
        最近更新 更多