10

クエリ バージョン 2 が非常に高速なのはなぜですか?

DB エンジンがテーブル値関数の "GetUsageStatistic" を複数回呼び出していると思われます。そのため、"GetUsageStatistic" が決定論的であり、一度だけ呼び出す必要があることをエンジンに伝える方法はありますか?

クエリ バージョン 1

--Takes ~10 minutes
select *
from RosterLevel r
left join GetUsageStatistics( @mindate, @maxdate ) usage on r.UserID = usage.UserID;

クエリ バージョン 2

--Takes ~10 seconds
select * into #usage from  GetUsageStatistics( @mindate, @maxdate );
select *
from RosterLevel r
left join #usage on r.UserID = #usage.UserID;
4

2 に答える 2

1

コメントで述べたように、最良の答えは、吐き出された実行計画を分析することです。それを除けば、あなたの直感はおそらく正しいでしょうが、SQL Server が自動的に試行するキャッシングを除けば、関数が決定論的であることを示すために提供できるクエリ ヒントについてはあまり頭に浮かびませんが、ぜひ試してみてください。Query Hints MSDN pageに記載されているいくつかのこと。私の最初のテストは、おそらくTable Hintsを利用するでしょう。

于 2011-06-06T20:18:39.820 に答える
0

If you use the function in your first example, it is called many times -- once for each record in your RosterLevel table. It returns a (potentially) different table each time, depending on the join field.

If you use the function in your second example, it is only called once. From there, the table variable is in memory, and you're not having to do a read over and over.

于 2011-06-14T17:28:16.097 に答える