I have a strange scenario with executing a function related to a table. Basically, I have a built-in table-value function that takes DATETIME as a parameter.
It looks like this (not quite so):
CREATE FUNCTION fn_MyFunction(@StartDate DATETIME) RETURNS TABLE AS RETURN ( SELECT COUNT(*), CustomerID, SUM(PAID) FROM Orders WHERE OrderDate > @StartDate GROUP BY CustomerID )
Now I am trying to investigate a problem in which this request has been running for> 1 minute. It turns out if I call the request this way:
SELECT * FROM fn_MyFunction('7/1/2011')
It lasts> 1 minute.
However, if I call the request this way:
DECLARE @startDate DATETIME = '7/1/2011' SELECT * FROM fn_MyFunction(@startDate)
He passes in a second. SQL Server uses completely different explanation plans for both calls.
Obviously, I want it to execute the second method all the time, unfortunately, I call this function with a table using LINQ 2 SQL, which will not declare an intermediate variable.
Is there a way that I can use an intermediate variable in an inline table function? I really don't want to convert this to a multi-valued table function. Other ideas are also welcome. I am a little puzzled.
source share