比较SQL计数结果与先前的结果值-自上次选择计数以来有多少新记录

问题描述 投票:3回答:3

我有一个在表上插入新值的脚本。当我select count(*)显示结果。当我重复查询时,有没有办法将此值与新值进行比较?

考虑到脚本仍在插入新值,我想知道自上次选择计数以来有多少新记录。

sql sql-server tsql sql-server-2014
3个回答
2
投票

您不容易做到这一点,因为每次运行查询时(如果手动运行),它将重置您拥有的所有变量。我可以想到3个选项:

  1. 类似于Gordon的代码,但是每次运行时都必须手动保存该值
declare @saved_count int = 0; -- THIS MUST BE MANUALLY UPDATED EACH TIME YOU RUN IT

-- Get the different since the last run
select count(*)-@saved_count
from MyTable;

-- Get the current value => manually copy to @saved_count above
select count(*)
from MyTable;
  1. 根据Lukasz的回答,将值存储在更永久的存储中(您可以使用全局临时表,一旦断开连接,该表将不受影响,这不会影响生产。)]]

  2. 您可以按以下方式运行自动查询,该查询可跟踪当前值并定期为您打印一些详细信息。

  3. declare @CurrentCount int = 0, @LastCount int = 0;
    
    while 1 = 1 begin
      select @CurrentCount = count(*)
      from MyTable;
    
      select getdate(), @CurrentCount - @LastCount;
      raiserror('Force a buffer flush',0,1) with nowait;
    
      set @LastCount = @CurrentCount;
    
      waitfor delay '00:00:10'; -- Wait 10s
    end
    

1
投票

您可以实现它:


0
投票

通常,您不能这样做。但是,如果您的表中有一个标识列您可能还记得它

© www.soinside.com 2019 - 2024. All rights reserved.