Last active
June 1, 2022 13:46
-
-
Save Azsaturndx/0b7d70879c241f4c8d347b1fa18235bb to your computer and use it in GitHub Desktop.
IPMT Function (Interest payment) - SQL Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Interest Payment | |
* (SQL Server) | |
* AzsaturnDx (2020) - No copyright at all | |
* | |
* Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. | |
* | |
* @Rate FLOAT - Required. The interest rate per period. | |
* @Period INT - Required. Specifies the period and must be in the range 1 to nper. | |
* @Periods INT - Required. The total number of payment periods in an annuity. | |
* @Present FLOAT - Required. The present value — the total amount that a series of future payments is worth now. | |
* @Future FLOAT - Optional. The future value, or a cash balance you want to attain after the last payment is made. If don't needed pass 0 as value | |
* @Type - Optional. The number 0 or 1 and indicates when payments are due. | |
* @return FLOAT Interest payment by given period | |
* | |
* @Example | |
* SELECT dbo.IPMT(0.00673,1,104,-50000,0,0) | |
* | |
* REQUIRES: dbo.PMT , dbo.FV | |
* Required functions are available @: https://gist.github.com/Azsaturndx/8ce3e47e2d3210a65fc83b09ac32da5f | |
*/ | |
CREATE FUNCTION [dbo].[IPMT] | |
(@Rate FLOAT | |
,@Period INT | |
,@Periods INT | |
,@Present FLOAT | |
,@Future FLOAT | |
,@Type INT) | |
RETURNS FLOAT | |
BEGIN | |
SET @Type = ISNULL(@Type,0); | |
DECLARE @Payment AS FLOAT = (SELECT dbo.PMT(@Rate,@Periods,@Present,@Future,@Type)) | |
DECLARE @Interest AS FLOAT = 0.0; | |
IF @Period=1 | |
BEGIN | |
IF @Type=1 | |
BEGIN | |
SET @Interest=0 | |
END --IF @Type=1 | |
ELSE | |
BEGIN | |
SET @Interest=-@Present | |
END | |
END --IF @Period=1 | |
ELSE --IF @Period <> 1 | |
BEGIN | |
IF @Type=1 | |
BEGIN | |
SET @Interest=dbo.FV(@Rate,@Period-2,@Payment,@Present,1)-@Payment | |
END --IF @Type=1 | |
ELSE --IF @Type<>1 | |
BEGIN | |
SET @Interest = dbo.FV(@Rate,@Period-1,@Payment,@Present,0) | |
END --IF @Type<>1 | |
END ----IF @Period <> 1 | |
RETURN @Interest*@Rate | |
END; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment