Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a query execute so much faster when I (manually) cache the results of a table-valued function in a temporary table?

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;
like image 699
Triynko Avatar asked Jun 02 '11 21:06

Triynko


1 Answers

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.

like image 174
Taylor Gerring Avatar answered Oct 26 '22 12:10

Taylor Gerring