Calculate Value Dynamically
I found this 'running totals' CTE example here (you should be able to adapt it to your needs). Note the MAXRECURSION
https://stackoverflow.com/questions/11310877/calculate-running-total-running-balance

DECLARE @Tbl TABLE (RowNum INT,Columnx INT)

INSERT INTO @Tbl (RowNum,Columnx)
VALUES (1,100)

INSERT INTO @Tbl (RowNum,Columnx)
VALUES (2,200)

INSERT INTO @Tbl (RowNum,Columnx)
VALUES (3,300)
;
WITH x
AS (
    SELECT RowNum
        ,Columnx
        ,RunningTotal = Columnx
    FROM @tbl
    WHERE RowNum = 1

    UNION ALL

    SELECT y.RowNum
        ,y.Columnx
        ,x.RunningTotal + y.Columnx
    FROM x
    INNER JOIN @tbl AS y ON y.RowNum = x.RowNum + 1
    )
SELECT RowNum
    ,columnx
    ,RunningTotal
FROM x
ORDER BY rownum
OPTION (MAXRECURSION 10000);