Loan Amortisation in SQL Server (PMT, FV, IPMT, PPMT)
Whilst designing a data warehouse for a banking client recently, I needed to calculate projected future loan payments (including breaking this down by interest and capital payments) for every customer throughout the life of the loan.
In Excel this is a pretty simple job, as Microsoft helpfully provide a number of functions to do just that (namely PMT, FV, IPMT and PPMT). In SQL Server however we do not have the luxury of having ready made functions, so I set about making my own.
Initially I coded them up as SQL Server functions, only to find that the internal rounding that SQL performs renders the results too inacurate to be usable. It was therefore necessary to write the functions in a C#, and wrap them up in a CLR library. SQL Server can then import them as scalar functions, to be used by any query that requires them.
To overcome this, the Purple Frog team have written a .Net CLR library which add four loan amortisation functions to SQL Server, which can be called from within a query as scalar functions, such as:
SELECT dbo.PMT(@APR/12.0, @Term, @LoanValue, 0, 0)
The functions provided are:
- PMT (The monthly payment of a loan)
- FV (The future value of a loan at a given month)
- IPMT (The interest portion of the monthly payment at a given month)
- PPMT (The capital portion of the monthly payment at a given month)
These are designed to mirror the parameters and results of the Excel functions, and have been written in C# using Visual Studio 2008, and tested against SQL Server 2008 Enterprise.
The functions perform surprisingly well; in tests I was able to calculate over 3 million monthly payments per minute, and that was on a relatively underpowered development server.
You can download the C# code, or the pre-compiled binary from the Frog-Blog download section.