首先,对问题的一般描述:我正在运行一个定期进程,它会更新表格中的总数。问题是,流程的每次执行都可能需要多次更新,并且每次执行都取决于之前的结果。
我的问题是,可以在单个 SQL Server SP 中完成吗?
我的代码(我对其进行了一些更改以简化示例):
INSERT INTO CustomerMinuteSessions(time, customer, sessions, bytes, previousTotalSessions)
SELECT MS.time,
MS.customer,
MS.totalSessions,
MS.totalBytes,
CTS.previousTotalSessions
FROM (SELECT time, customer, SUM(sessions) as totalSessions, SUM(bytes) AS totalBytes
FROM MinuteSessions
WHERE time > @time
GROUP BY time, x) MS
CROSS APPLY TVF_GetPreviousCustomerTotalSessions(MS.customer) CTS
ORDER BY time
该previousTotalSessions
列依赖于 中的其他行UpdatedTable
,其值由CROSS APPLY
ing检索TVF_GetPreviousCustomerTotalSessions
,但如果我按原样执行 SP,则所有行都使用函数检索到的值,而不采用SP 执行期间添加的行。
为了完整起见,这里是TVF_GetPreviousCustomerTotalSessions
:
FUNCTION [dbo].[TVF_GetCustomerCurrentSessions]
(
@customerId int
)
RETURNS @result TABLE (PreviousNumberOfSessions int)
AS
BEGIN
INSERT INTO @result
SELECT TOP 1 (PreviousNumberOfSessions + Opened - Closed) AS PreviousNumberOfSessions
FROM CustomerMinuteSessions
WHERE CustomerId = @customerId
ORDER BY time DESC
IF @@rowcount = 0
INSERT INTO @result(PreviousNumberOfSessions) VALUES(0)
RETURN
END
什么是最好的(即没有for循环,我猜......)在查询中获取后续行的前一行?