SQL Server 2000和2005版并没有提供很多金融函数,但是有很多金融计算公式的来源,在这篇技巧中,我将展示净现值(present value (PV))和未来值(future value (FV))函数,它们都是标量的用户自定义函数(UDF)。
以下是PV的基本逻辑:给定一个未来的值,一个利率和复利计算时期,PV的计算可以确定现在投资的价值,其公式为:
PV = FV [ 1 / (1 + i)n ]
列表A展示了将其转换为一个SQL Server的UDF并不是一件很困难的事。
-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Arthur Fuller
-- Create date: 22-Aug-2006
-- Description: Returns Present Value
-- Example:
-- @fv = 150000 (dollars)
-- @i = 6% (per annum)
-- @p = 5 (years)
-- SELECT DBO.PV_fn( 100000, .06, 5)
-- returns 150000
-- =============================================
CREATE FUNCTION PV_fn
(
-- Add the parameters for the function here
@fv float, -- future value desired
@i decimal, -- interest rate
@p int -- number of compounding periods
)
RETURNS money
AS
BEGIN
-- Declare the return variable here
DECLARE @Result money
-- Add the T-SQL statements to compute the return value here
SELECT @Result = @fv *(1/Power((1+@i),@p))
-- Return the result of the function
RETURN @Result
END
GO
与PV相反的就是FV,它的含义是:给定现在的货币量、利率和复利计算时期,您的钱在时期结束时的价值。
其计算公式为:
FV = PV (1 + i)n
当您将这一公式翻译为SQL Server函数的时候,您会得到列表B中所示的代码:
-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Arthur Fuller
-- Create date: 22-Aug-2006
-- Description: Returns Future Value
-- Example:
-- @fv = 100000 (dollars)
-- @i = 6% (per annum)
-- @p = 5 (years)
-- SELECT DBO.FV_fn( 150000, .06, 5)
-- returns 100000
-- =============================================
CREATE FUNCTION FV_fn
(
-- Add the parameters for the function here
@pv float, -- current amount in dollars
@i decimal, -- interest rate
@p int -- number of compounding periods
)
RETURNS money
AS
BEGIN
-- Declare the return variable here
DECLARE @Result money
-- Add the T-SQL statements to compute the return value here
SELECT @Result = @pv *Power((1+@i),@p)
-- Return the result of the function
RETURN @Result
END
GO
责任编辑:张琎
用户评论