Parameter Sniffing, 查執行計畫語法
Parameter Sniffing 參數探測
來源:https://www.brentozar.com/archive/2013/06/the-elephant-and-the-mouse-or-parameter-sniffing-in-sql-server/、
https://msdn.microsoft.com/zh-tw/library/dn168870.aspx
有時候會發生重用錯誤執行計畫的情況,如果執行計畫的編譯值和執行值的資料量差異過大時,將可能嚴重影響查詢效能,
而主因就是參數探測(parameter sniffing)所導致。
翻譯:執行SP時,因輸入參數不同所以編譯值和執行值的資料量差異過大,卻重用編譯時建立的執行計畫,導致大量耗費查詢效能
解決方法:
- sp使用with recompile
這方法查詢時將不會重用執行計畫。
- 使用本機變數取代參數
如果你不想失去重用執行計畫所帶來的好處,那麼你可以使用區域變數取代參數(可能須改寫SP),這樣會建立一個通用執行計畫(統計值估算均相同)。
- 使用recompile查詢提示
該方法查詢時將不會重用執行計畫。
- 使用OPTIMIZE FOR, OPTIMIZE FOR UNKNOWN 查詢提示
OPTIMIZE FOR UNKNOWN 是SQL2008後才支援
---------------------------以下是查詢執行計畫語法---------------------------------
select
bucketid,
a.plan_handle,
refcounts,
usecounts,
execution_count,
size_in_bytes,
cacheobjtype,
objtype,
text,
query_plan,
creation_time,
last_execution_time,
execution_count,
total_elapsed_time,
last_elapsed_time
from sys.dm_exec_cached_plans a
inner join sys.dm_exec_query_stats b on a.plan_handle=b.plan_handle
cross apply sys.dm_exec_sql_text(b.sql_handle) as sql_text
cross apply sys.dm_exec_query_plan(a.plan_handle) as query_plan
where 1=1
and text like '%mybadproc%' --此處放置您要查詢的語法
-- and a.plan_handle = 0x06000B00C96DEC2AB8A16D06000000000000000000000000
and b.last_execution_time between '2014-01-20 09:00' and '2014-01-20 12:00'
order by last_execution_time desc