views:

93

answers:

1

I'm looking for a good approach for calculating and caching periodic opening account balances using SQL.

I know I can use SQL to sum up a bunch of transactions from start of time to the start of the period in question, but I'm more interested in whether its worth caching those calculated balances (at various points in time) in another table? Obviously this would require invalidating that table when older transactions are edited.

I'm just not sure if it's worth the hassle, if there's an easier way to do it, or just some general advice on the issue.

Assume many of transactions though mostly spread across many accounts, so many transactions would be filtered out of the calculation. I'm using SQL Server 2008 and OK to use features specific to it.

Currently I'm using:

    public Decimal GetAccountBalance(DateTime forDate)
    {
        var sum=(from t in m_dc.Transactions
            where t.date<forDate && t.account_id==m_CurrentAccount.id
            select (decimal?)t.amount).Sum();

        return sum==null ? 0 : (decimal)sum;
    }
+2  A: 

If I understand correctly you are asking about caching the result of a sum.

My thoughts on this are, why bother trying to optimize when you don't know its going to be an issue? You could just be adding unnecessary complexity and taking unneeded time.

Tetraneutron
Yes measure before optimising
Mark
You're right of course... it's just that there's something about repeatedly adding this stuff up on every page view really bothers me. (normally I develop real-time music software where performance is critical - and I spend considerable effort not to waste anything. I guess I just need to let that go for this project :)Thanks anyway.
cantabilesoftware