Here is my question,
I have a view calling another view. And that second view has a scalar function which obviously runs for each row of the table. For only 322 rows, it takes around 30 seconds. When I take out the calculated field, it takes 1 second.
I appreciate if you guys give me an idea if I can optimize the function or if there is any other way to increase the performance?
Here is the function:
ALTER FUNCTION [dbo].[fnCabinetLoad] (
@site nvarchar(15),
@cabrow nvarchar(50),
@cabinet nvarchar(50))
RETURNS float
AS BEGIN
-- Declare the return variable here
DECLARE @ResultVar float
-- Add the T-SQL statements to compute the return value here
SELECT @ResultVar = SUM(d.Value)
FROM
(
SELECT dt.*,
ROW_NUMBER()
OVER (PARTITION BY dt.tagname ORDER BY dt.timestamp DESC) 'RowNum'
FROM vDataLog dt
WHERE dt.Timestamp BETWEEN dateadd(minute,-15,getdate()) AND GetDate()
) d
INNER JOIN [SKY_EGX_CONFIG].[dbo].[vPanelSchedule] AS p
ON p.rpp = left(d.TagName,3) + substring(d.TagName,5,5)
+ substring(d.TagName,11,8)
AND right(p.pole,2) = substring(d.TagName,23,2)
AND p.site = @site
AND p.EqpRowNumber = @cabrow
AND p.EqpCabinetName= @cabinet
WHERE d.RowNum = 1
AND Right(d.TagName, 6) = 'kW Avg'
RETURN @ResultVar
END
BETWEEN dateadd(minute,-15,getdate()) AND GetDate()..this is computed for each and every row even through it will be the same value always!! Oh, the performance!