我有一个在表上插入新值的脚本。当我select count(*)
显示结果。当我重复查询时,有没有办法将此值与新值进行比较?
考虑到脚本仍在插入新值,我想知道自上次选择计数以来有多少新记录。
您不容易做到这一点,因为每次运行查询时(如果手动运行),它将重置您拥有的所有变量。我可以想到3个选项:
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
您可以实现它:
通常,您不能这样做。但是,如果您的表中有一个标识列您可能还记得它