Skip to content

Instantly share code, notes, and snippets.

@Azsaturndx
Last active October 14, 2022 18:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Azsaturndx/bd073bfe17cc9c437949a73084c9dcc0 to your computer and use it in GitHub Desktop.
Save Azsaturndx/bd073bfe17cc9c437949a73084c9dcc0 to your computer and use it in GitHub Desktop.
PMT Function (Payment) - SQL Server
/**
* Payment (PMT)
* (SQL Server)
* AzsaturnDx (2020) - No copyright at all
*
* Calculates the payment for a loan based on constant payments and a constant interest rate.
*
* @Rate FLOAT - Required. The interest rate for the loan.
* @Periods INT - Required. The total number of payments for the loan.
* @Present FLOAT - Required. The present value, or the total amount that a series of future payments is worth now; also known as the principal.
* @Future FLOAT - Optional. The future value, or a cash balance you want to attain after the last payment is made. If fv is omitted, it is assumed to be 0 (zero), that is, the future value of a loan is 0.
* @Type INT - Optional. The number 0 (zero) or 1 and indicates when payments are due. (0 = End of Period , 1 = Start of Period)
* @return FLOAT Payment
*
* @Example
* SELECT dbo.PMT(.20,12,1,2,0)
*
* More financial functions are available @: https://gist.github.com/Azsaturndx/8ce3e47e2d3210a65fc83b09ac32da5f
*/
CREATE FUNCTION [dbo].[PMT]
(@Rate FLOAT
,@Periods INT
,@Present FLOAT
,@Future FLOAT
,@Type INT)
RETURNS FLOAT
BEGIN
SET @Type = ISNULL(@Type, 0);
SET @Future = ISNULL(@Future, 0);
DECLARE @Result AS FLOAT = 0;
DECLARE @Term AS FLOAT = 0;
IF @Rate=0
BEGIN
SET @Result=(@Present+@Future)/@Periods;
END --IF @Rate=0
ELSE
BEGIN --IF @Rate <> 0
SET @term = POWER(1+@rate, @periods);
IF @Type=1
BEGIN
SET @Result = (@Future*@Rate / (@Term-1) + @Present*@Rate / (1-1/@Term)) / (1+@Rate)
END
ELSE
BEGIN
SET @Result = @Future*@Rate/(@term-1)+@Present*@Rate / (1-1/@Term)
END
END --IF @Rate <> 0
RETURN -@Result
END;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment