I am using sql server as back-end for developing my application in asp.net c#. Now i need to create a table with an auto calculating column(closing balance) as shown below:<
Seems to me like you don't need really need recursion...
CREATE FUNCTION dbo.GetClosingBalance(@Date date) RETURNS int AS
BEGIN
DECLARE @RetVal int
SELECT
@RetVal = SUM([in stock]) - SUM([out stock])
FROM
x
WHERE
[Date] <= @Date
RETURN @RetVal
END
ALTER TABLE x ADD COLUMN [closing balance] AS (dbo.GetClosingBalance([Date]))
Assumption
1.Your table structure is like
Date | In Stock | Out Stock
2.You will insert a New Columns before calculating the balance
.
3.Date is an Primary Column
(Unique + Not NULL)
Taking the above assumptions:
You have make a SP if you want to use in C#
1.Create a temp table and assigned Row Number
using Rank()
select
rank() OVER (ORDER BY [Date]) as [Rank],
t1.[Date],
t1.[in stock],
t1.[out stock]
--,t1.[in stock]-t1.[out stock] balance
into #temp1
from (your table name)
;
2.Now you will be using the above temp table
to get the Balance
WITH x AS
(
SELECT
[Rank],
[Date],
[in stock],
[out stock],
bal=([in stock]-[out stock])
FROM #temp1
WHERE [Rank] = 1
UNION ALL
SELECT
y.[Rank],
y.[Date],
y.[in stock],
y.[out stock],
x.bal+(y.[in stock]-y.[out stock])
FROM x INNER JOIN #temp1 AS y
ON y.[Rank] = x.[Rank] + 1
)
SELECT
[Date],
[in stock],
[out stock],
Balance = bal
FROM x
ORDER BY Date
OPTION (MAXRECURSION 10000);
Here is the SQL Fiddle where you can verify.