我有一个在表格中插入新值的脚本。当我选择 count(*)
时,会显示结果。当我重复查询时,有没有办法将这个值与新值进行比较?
考虑到脚本仍在插入新值,我想知道自上次选择计数以来有多少新记录。
最佳答案
您无法轻易做到这一点,因为每次您运行查询(如果手动运行),它都会重置您拥有的所有变量。我能想到 3 个选项:
- 类似于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;
按照 Lukasz 的回答将值存储在更永久的存储中(您可以使用全局临时表,一旦连接断开,它就会消失,这不会影响生产)。
您可以按如下方式运行自动查询,它会跟踪当前值并定期为您打印一些详细信息。
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
关于sql - 将 SQL 计数结果与之前的结果值进行比较 - 自上次选择以来有多少新记录计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55601694/