Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 function produces value but then returns null

Author  Topic 

silver_surfer21
Starting Member

21 Posts

Posted - 2011-03-09 : 11:44:31
Can anyone tell me why this function code produces a monetary value in @CurrentValue exactly as I'd expect but then decides its null when it comes to returning it?


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
ALTER FUNCTION FindCurrentValue
(
-- Add the parameters for the function here
@Postcode nvarchar(50),@Application_Date date,@HouseType nvarchar(50), @decPrice money
)
RETURNS money

AS
BEGIN
-- Declare the return variable here
DECLARE @currentValue money
DECLARE @CurrentYear int
DECLARE @CurrentMonth int
DECLARE @NoOfLoops int
DECLARE @CurrentLoop int
DECLARE @CurrentAverage decimal

SET @CurrentYear = YEAR(@Application_Date)
SET @currentValue = @decPrice
set @CurrentMonth = MONTH(@Application_DATE)

WHILE(@CurrentYear <=YEAR(GETDATE()))
BEGIN
SET @CurrentLoop =0


IF(YEAR(GETDATE()) = @CurrentYear)
BEGIN
SET @NoOfLoops = MONTH(GETDATE())-@CurrentMonth
END

IF(@CurrentYear = YEAR(@Application_Date))
BEGIN
SET @NoOfLoops = 12 - MONTH(@Application_Date)
END

IF(@CurrentYear >YEAR(@Application_Date) AND @CurrentYear < YEAR(GETDATE()))
BEGIN
SET @NoOfLoops = 12
END

SELECT @CurrentAverage = (SELECT Top 1 Avg_Monthly_Increase FROM YearlyAverageIncrease WHERE @Postcode = Postcode AND @HouseType = HouseType AND YEAR = @CurrentYear)


WHILE(@CurrentLoop < @NoOfLoops)
Begin

-- Add the T-SQL statements to compute the return value here
SET @currentValue = @CurrentValue + ((@currentValue/100) * @CurrentAverage)

SET @CurrentLoop = @CurrentLoop +1
END

Set @CurrentYear = @CurrentYear +1
SET @CurrentLoop = @CurrentLoop +1
END


-- Return the result of the function
RETURN @CurrentValue

END
GO

pk_bohra
Master Smack Fu Yak Hacker

1182 Posts

Posted - 2011-03-09 : 11:56:19
quote:

SET @currentValue = @CurrentValue + ((@currentValue/100) * @CurrentAverage)




Shot in dark

SET @currentValue = @CurrentValue + ((@currentValue/100) * isnull(@CurrentAverage,0))
Go to Top of Page

lappin
Posting Yak Master

182 Posts

Posted - 2011-03-09 : 12:05:44
I think you could replace your looping logic with a more set based approach, using Group by:

e.g select avg(Price),Postcode,
YEAR( [DateCol])as Yr,MONTH( [DateCol])as Mnth from tableName
group by YEAR( [DateCol]),MONTH( [DateCol]),Postcode
Go to Top of Page
   

- Advertisement -