November 3, 2016 at 10:47 am
We have a heavily used GUI that displays specific business data in a pivot.
A stored procedure is used to create the pivot, using dynamic SQL.
The SP is using EXEC sp_executesql with parameters in the following way:
SET @SQL = 'select * from (select '+@Cols+' from #X) StdP PIVOT (COUNT(DateStamp) FOR DateStamp IN ('+@Pivot+')) as PVT order by '+@Cols2+''
EXEC sp_executesql @SQL,
N'@_Cols varchar(100), @_Cols2 varchar(100), @_Pivot varchar(5000)',
@_Cols = @Cols, @_Cols2 = @Cols2, @_Pivot = @Pivot
****@Pivot can and most of the time is, will be different on each execution.
The plan cache is overflowing with many prepared, single use execution plans.
How can this be avoided?
Thanks in advance.
November 3, 2016 at 11:32 am
scott.laird (11/3/2016)
We have a heavily used GUI that displays specific business data in a pivot.A stored procedure is used to create the pivot, using dynamic SQL.
The SP is using EXEC sp_executesql with parameters in the following way:
SET @SQL = 'select * from (select '+@Cols+' from #X) StdP PIVOT (COUNT(DateStamp) FOR DateStamp IN ('+@Pivot+')) as PVT order by '+@Cols2+''
EXEC sp_executesql @SQL,
N'@_Cols varchar(100), @_Cols2 varchar(100), @_Pivot varchar(5000)',
@_Cols = @Cols, @_Cols2 = @Cols2, @_Pivot = @Pivot
****@Pivot can and most of the time is, will be different on each execution.
The plan cache is overflowing with many prepared, single use execution plans.
How can this be avoided?
Thanks in advance.
Do you have "Optimize for Ad Hoc Queries" enabled?
--Jeff Moden
Change is inevitable... Change for the better is not.
November 4, 2016 at 4:05 am
yes....optimize for adhoc is on
November 4, 2016 at 4:17 am
From Glenn Berry's diagnostic queries series:
-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache (Query 44) (Ad hoc Queries)
SELECT TOP(50) [text] AS [QueryText], cp.cacheobjtype, cp.objtype, cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
WHERE cp.cacheobjtype = N'Compiled Plan'
AND cp.objtype IN (N'Adhoc', N'Prepared')
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC OPTION (RECOMPILE);
-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this.
-- Enabling forced parameterization for the database can help, but test first!
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply