Why is Query Version 2 so much faster?
I suspect the DB Engine is calling the Table-Valued-Function "GetUsageStatistic" multiple times, so is there a way to tell the engine that "GetUsageStatistic" is deterministic and should be called only once?
Query Version 1
--Takes ~10 minutes
select *
from RosterLevel r
left join GetUsageStatistics( @mindate, @maxdate ) usage on r.UserID = usage.UserID;
Query Version 2
--Takes ~10 seconds
select * into #usage from GetUsageStatistics( @mindate, @maxdate );
select *
from RosterLevel r
left join #usage on r.UserID = #usage.UserID;
As mentioned in the comments, the best answer is to analyze whatever execution plan is spit out. Barring that, your intuition is probably right, but aside from whatever caching SQL Server automatically attempts, there's not much coming to my head in the way of query hints you can provide to indicate that the function is deterministic, but you're welcome to try a few things out mentioned in the Query Hints MSDN page. My first tests would probably draw on Table Hints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With