我有以下TSQL语句,我试图弄清楚如何继续获取结果(一次100行),将它们存储在变量中(因为我必须在每次选择后添加总计)和继续在while循环中选择,直到找不到更多记录,然后将变量totals返回给调用函数。
SELECT [OrderUser].OrderUserId, ISNULL(SUM(total.FileSize), 0), ISNULL(SUM(total.CompressedFileSize), 0)
FROM
(
SELECT DISTINCT TOP(100) ProductSize.OrderUserId, ProductSize.FileInfoId,
CAST(ProductSize.FileSize AS BIGINT) AS FileSize,
CAST(ProductSize.CompressedFileSize AS BIGINT) AS CompressedFileSize
FROM ProductSize WITH (NOLOCK)
INNER JOIN [Version] ON ProductSize.VersionId = [Version].VersionId
) AS total RIGHT OUTER JOIN [OrderUser] WITH (NOLOCK) ON total.OrderUserId = [OrderUser].OrderUserId
WHERE NOT ([OrderUser].isCustomer = 1 AND [OrderUser].isEndOrderUser = 0 OR [OrderUser].isLocation = 1)
AND [OrderUser].OrderUserId = 1
GROUP BY [OrderUser].OrderUserId
答案 0 :(得分:2)
根据聚集索引,如果是编号为id,则使用下面的代码。如果是按日期,则以10 - 60分钟为增量。关注其他事情的表现,但是这段代码的可爱部分是你可以随时开始和停止,如果你把结果推到永久临时表(真正的表,只是临时)
以下是一个示例:
declare @count int
Declare @batch int
declare @max int
create table #temp (id int identity(1,1) primary key, Batch int, value int)
select @max = max(OrderUserId), @count = 0, @batch = 1000 from table
while (@count < @max)
begin
insert into #temp (batch,value)
select @count, Sum(stuffs)
from table
where orderId >= @count
and orderid < @count + @batch
Set @count = @count + @batch
waitfor delay ('00:00:01')
Raiserror('On Batch %d',0,1,@Count) with nowait /* Will print progess */
end