I have this function-- =============================================-- Author: <Author,,Name>-- Create date: <Create Date, ,>-- Description: <Description, ,>-- =============================================CREATE FUNCTION FindCurrentValue ( -- Add the parameters for the function here @Postcode nvarchar(50),@Application_Date date,@HouseType nvarchar(50), @decPrice money)RETURNS intASBEGIN -- 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 @currentValueEND
which takes data about a property and its price when bought, and uses an average of price increases on that type of property in order to calculate an estimate of what that property should be worth now. As far as I can tell everything works properly but the function is horribly slow, taking around 15 minutes to calculate the predicted value for one record. This is not really feasible for the number of records I need to run through it, and so I'm wondering if there's any way to speed the process up.I suspect the loops are horribly inefficient being new to sql don't know a way around using them