Skip to content

Commit 8a0ff5d

Browse files
BrentOzarclaude
andcommitted
sp_BlitzCache: speed up @SlowlySearchPlansFor by skipping the XML cast
Switch the @SlowlySearchPlansFor predicate from CAST(qp.query_plan AS NVARCHAR(MAX)) LIKE ... to tqp.query_plan LIKE ..., where tqp comes from sys.dm_exec_text_query_plan. That DMV returns the plan as NVARCHAR(MAX) directly, so we skip the per-row XML-to-string cast that dominated the search cost. The extra CROSS APPLY is only added when @SlowlySearchPlansFor is set, so non-search runs pay nothing. The existing qp (XML) apply stays in place because the rest of sp_BlitzCache still needs it for .exist() / .value() shredding and for @Noobsaibot. Fixes BrentOzarULTD#3936. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 324ec1d commit 8a0ff5d

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

sp_BlitzCache.sql

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2129,7 +2129,10 @@ IF @SlowlySearchPlansFor IS NOT NULL
21292129
BEGIN
21302130
RAISERROR(N'Setting string search for @SlowlySearchPlansFor, so remember, this is gonna be slow', 0, 1) WITH NOWAIT;
21312131
SET @SlowlySearchPlansFor = REPLACE((REPLACE((REPLACE((REPLACE(@SlowlySearchPlansFor, N'[', N'_')), N']', N'_')), N'^', N'_')), N'''', N'''''');
2132-
SET @body_where += N' AND CAST(qp.query_plan AS NVARCHAR(MAX)) LIKE N''%' + @SlowlySearchPlansFor + N'%'' ' + @nl;
2132+
/* Search against sys.dm_exec_text_query_plan, which returns NVARCHAR(MAX) directly
2133+
and skips the per-row XML-to-string cast that CAST(qp.query_plan AS NVARCHAR(MAX)) pays.
2134+
Issue #3936. */
2135+
SET @body_where += N' AND tqp.query_plan LIKE N''%' + @SlowlySearchPlansFor + N'%'' ' + @nl;
21332136
END
21342137

21352138

@@ -2183,6 +2186,13 @@ SET @body += N') AS qs
21832186
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
21842187
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp ' + @nl ;
21852188

2189+
IF @SlowlySearchPlansFor IS NOT NULL
2190+
BEGIN
2191+
/* Only pay for the text plan when the user is actually searching strings.
2192+
Issue #3936. */
2193+
SET @body += N' CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, 0, -1) AS tqp ' + @nl ;
2194+
END
2195+
21862196
IF @VersionShowsAirQuoteActualPlans = 1
21872197
BEGIN
21882198
SET @body += N' CROSS APPLY sys.dm_exec_query_plan_stats(qs.plan_handle) AS deqps ' + @nl ;

0 commit comments

Comments
 (0)