Sunday, August 3, 2014

SQL Server Query Plan differs for Same Set of values

Yes, that's correct. So what is your question? We're no mind readers, but let my try my Crystal Ball (TM)..



Well, the fog get's clearer now. Run



SELECT TOP 100
creation_time ,
last_execution_time ,
total_worker_time / 1000 AS total_worker_time ,
total_logical_reads ,
total_logical_writes ,
execution_count ,
total_logical_reads + total_logical_writes AS total_logical ,
CASE WHEN sql_handle IS NULL THEN ' '
ELSE ( SUBSTRING(st.text, ( qs.statement_start_offset + 2 ) / 2,
( CASE WHEN qs.statement_end_offset = -1 THEN LEN(CONVERT(NVARCHAR(MAX), st.text)) * 2
ELSE qs.statement_end_offset
END - qs.statement_start_offset ) / 2) )
END AS query_text ,
st.text AS sql_text ,
qp.query_plan ,
cp.cacheobjtype ,
cp.objtype
FROM sys.dm_exec_query_stats qs
INNER JOIN sys.dm_exec_cached_plans cp ON cp.plan_handle = qs.plan_handle
CROSS APPLY sys.dm_exec_sql_text(sql_handle) st
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE total_logical_reads + total_logical_writes > 0
ORDER BY total_logical DESC;



after the first SELECT and after the EXECUTE. Take a look at the objtype column. One is an adhoc plan the other is a prepared one. Thus you get different ones. The first is optimal for the concrete literal. The other is parameterized.

No comments:

Post a Comment