To avoid plan cache bloat. Below is from contribution form:
Full Name
Paolo Piponi
Your Title
Systems Architect
By checking this box, I agree to the Brent Ozar Unlimited Code Contributor Licensing Agreement.
I agree!
Contributing to
sp_AskBrent®
Subject
Better paramterization for Query Stats inserts
Contribution Details
Obviously, this code won't run as it is but the changes should be clear. I've simply replaced the dynamic evaluation with parameters. We have a schedule for AskBrent and this avoids the plan cache filing up unnecessarily.
/* Populate #QueryStats. SQL 2005 doesn't have query hash or query plan hash. */
IF @@Version LIKE 'Microsoft SQL Server 2005%'
SET @StringToExecute = N'INSERT INTO #QueryStats ([sql_handle], Pass, SampleTime, statement_start_offset, statement_end_offset, plan_generation_num, plan_handle, execution_count, total_worker_time, total_physical_reads, total_logical_writes, total_logical_reads, total_clr_time, total_elapsed_time, creation_time, query_hash, query_plan_hash, Points)
SELECT [sql_handle], 2 AS Pass, GETDATE(), statement_start_offset, statement_end_offset, plan_generation_num, plan_handle, execution_count, total_worker_time, total_physical_reads, total_logical_writes, total_logical_reads, total_clr_time, total_elapsed_time, creation_time, NULL AS query_hash, NULL AS query_plan_hash, 0
FROM sys.dm_exec_query_stats qs
WHERE qs.last_execution_time >= @StartSampleTime ';
ELSE
SET @StringToExecute = N'INSERT INTO #QueryStats ([sql_handle], Pass, SampleTime, statement_start_offset, statement_end_offset, plan_generation_num, plan_handle, execution_count, total_worker_time, total_physical_reads, total_logical_writes, total_logical_reads, total_clr_time, total_elapsed_time, creation_time, query_hash, query_plan_hash, Points)
SELECT [sql_handle], 2 AS Pass, GETDATE(), statement_start_offset, statement_end_offset, plan_generation_num, plan_handle, execution_count, total_worker_time, total_physical_reads, total_logical_writes, total_logical_reads, total_clr_time, total_elapsed_time, creation_time, query_hash, query_plan_hash, 0
FROM sys.dm_exec_query_stats qs
WHERE qs.last_execution_time >= @StartSampleTime ';
EXECUTE sys.sp_executesql
@Statement=@StringToExecute,
@params=N'@StartSampleTime datetime',
@StartSampleTime=@StartSampleTime;