# IRR / NPV Calculations – T-SQL functionality for equivalent VBA functions?

Question : IRR / NPV Calculations – T-SQL functionality for equivalent VBA functions?

Hi All – My first ever post!

I have a client who wants a stored procedure to return a dataset that includes calculated NPV and IRR values.

Office components *cannot* be installed on the server, so I can’t do the obvious and pull the VBA functions in.

Has anybody seen sprocs or user-defined functions that correlate to the equivalent IRR and NPV functions (and return the same results, of course? 😉

Solution : IRR / NPV Calculations – T-SQL functionality for equivalent VBA functions?

I get roughly the same results than in Excel using the user-defined functions above

drop FUNCTION dbo.ufn_NPV
go

CREATE FUNCTION dbo.ufn_NPV(@rate decimal(30,10), @strIDs varchar(8000))
RETURNS decimal(30,10)
AS
BEGIN
&nbsp; DECLARE @t_IDs table(id int identity(0,1), value decimal(30,10))
&nbsp; DECLARE @strID varchar(12), @sepPos int
&nbsp; set @strIDs = coalesce(@strIDs + ‘,’, ”)
&nbsp; set @sepPos = charindex(‘,’, @strIDs)
&nbsp; WHILE @sepPos &gt; 0 &nbsp;BEGIN
&nbsp; &nbsp; &nbsp;SET @strID = LEFT(@strIDs, @sepPos – 1)
&nbsp; &nbsp; &nbsp;INSERT INTO @t_IDs(value) SELECT (CAST(@strID AS decimal(20,10))) where isnumeric(@strID)=1
&nbsp; &nbsp; &nbsp;SET @strIDs = RIGHT(@strIDs, DATALENGTH(@strIDs) – @sepPos)
&nbsp; &nbsp; &nbsp;set @sepPos = charindex(‘,’, @strIDs)
&nbsp; END
&nbsp; RETURN (select SUM(value/power(1+@rate, id)) from @t_IDs)
END
go

drop FUNCTION dbo.ufn_IRR
go

CREATE FUNCTION dbo.ufn_IRR(@strIDs varchar(8000), @guess decimal(30,10))
RETURNS decimal(30,10)
AS
BEGIN
&nbsp; DECLARE @t_IDs table(id int identity(0,1), value decimal(30,10))
&nbsp; DECLARE @strID varchar(12), @sepPos int, @NPV decimal(30,10)
&nbsp; set @strIDs = coalesce(@strIDs + ‘,’, ”)
&nbsp; set @sepPos = charindex(‘,’, @strIDs)
&nbsp; WHILE @sepPos &gt; 0 &nbsp;BEGIN
&nbsp; &nbsp; &nbsp;SET @strID = LEFT(@strIDs, @sepPos – 1)
&nbsp; &nbsp; &nbsp;INSERT INTO @t_IDs(value) SELECT (CAST(@strID AS decimal(20,10))) where isnumeric(@strID)=1
&nbsp; &nbsp; &nbsp;SET @strIDs = RIGHT(@strIDs, DATALENGTH(@strIDs) – @sepPos)
&nbsp; &nbsp; &nbsp;set @sepPos = charindex(‘,’, @strIDs)
&nbsp; END
&nbsp; set @guess = case when isnull(@guess, 0) &lt;= 0 then 0.00001 else @guess end
&nbsp; select @NPV = SUM(value/power(1+@guess, id)) from @t_IDs
&nbsp; WHILE @NPV &gt; 0
&nbsp; BEGIN
&nbsp; &nbsp; set @guess = @guess + 0.00001
&nbsp; &nbsp; select @NPV = SUM(value/power(1+@guess, id)) from @t_IDs
&nbsp; END
&nbsp; RETURN @guess
END

go

— values to compare with excel (note that for excel 0.00001 is 0.1%)
select dbo.ufn_irr(‘-90,13,14,15,16,17,18’, 0.00001) as irr,
dbo.ufn_npv(0.001, ‘-90,13,14,15,16,17,18’) as npv

HTH

Hilaire