在行插入时计算 运行 列平衡的函数

Function to compute running balance of column at row insertion

如何编写函数来计算图中所述的列值?

这是我试过的代码:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION RunningBal
(
    -- Add the parameters for the function here
    @Dr INT,
    @Cr INT,
    @Code NVARCHAR(5)
)
RETURNS INT
AS
BEGIN
    -- Declare the return variable here
    DECLARE @CurrentRunningBal INT

    -- Add the T-SQL statements to compute the return value here
    DECLARE @PreviouBal INT

    SET @PreviouBal = (SELECT TOP(1) [RunningBal] FROM Test WHERE Code = @Code ORDER BY ID DESC)

    if(@PreviouBal IS NULL)
     SET @PreviouBal = 0

    SET @CurrentRunningBal = @PreviouBal + @Dr - @Cr

    -- Return the result of the function
    RETURN @CurrentRunningBal

END
GO

当我尝试执行此操作时,出现以下错误并且不知道如何解决它。

最有可能的问题是您的列名称与函数名称完全相同 RunningBal,但我无法重现该行为。 在 Sql Server 2014 中,您可以使用 window 函数计算 运行 总数,例如:

DECLARE @t TABLE
    (
      id INT ,
      code CHAR(1) ,
      dramount MONEY ,
      cramount MONEY
    )
INSERT  INTO @t
VALUES  ( 1, 'a', 200, 0 ),
        ( 2, 'a', 250, 0 ),
        ( 3, 'b', 300, 0 ),
        ( 4, 'b', 0, 150 ),
        ( 5, 'a', 300, 0 ),
        ( 6, 'a', 100, 0 )


SELECT  * ,
        SUM(dramount - cramount) OVER ( PARTITION BY code ORDER BY id ) AS runningTotal
FROM    @t
ORDER BY id

输出:

id  code    dramount    cramount    runningTotal
1   a       200.00      0.00        200.00
2   a       250.00      0.00        450.00
3   b       300.00      0.00        300.00
4   b       0.00        150.00      150.00
5   a       300.00      0.00        750.00
6   a       100.00      0.00        850.00