将 SQL 计数结果与之前的结果值进行比较 - 自上次 select 计数以来有多少新记录

Compare a SQL count result with previous result value - how many new records since my last select count

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

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

你可以实现它:

CREATE TABLE tab_stat(id INT IDENTITY(1,1), t DATETIME DEFAULT GETDATE(), cnt BIGINT);

INSERT INTO tab_stat(cnt)
SELECT COUNT(*)
FROM tab_name;

SELECT *, cnt - LAG(cnt,1,0) OVER(ORDER BY id) AS diff
FROM tab_stat
ORDER BY id DESC;

db<>fiddle demo

一般情况下,您不能这样做。但是,如果您的 table 有一个标识列 您可以记住它 然后执行:

select count(*)
from t
where id > @saved_id;

如果可用,您可以对创作进行类似的操作 date/time。

当然,您必须将最大 ID(或创建时间)分配给一个变量,以便下次运行。

你不能轻易做到这一点,因为每次你 运行 你的查询(如果 运行 手动查询)它都会重置你拥有的任何变量。我能想到的有 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 的回答将值存储在更永久的存储中(您可以使用全局临时文件 table,一旦连接断开,它就会消失,这不会影响生产)。

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

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