@@ -330,6 +330,28 @@ SET @msg = N'New query_store_runtime_stats columns ' + CASE @new_columns
330330 END ;
331331RAISERROR (@msg, 0 , 1 ) WITH NOWAIT ;
332332
333+ /*
334+ This section determines if Parameter Sensitive Plan Optimization is enabled on SQL Server 2022+.
335+ */
336+
337+ RAISERROR (' Checking for Parameter Sensitive Plan Optimization ' , 0 , 1 ) WITH NOWAIT ;
338+
339+ DECLARE @pspo_out BIT ,
340+ @pspo_enabled BIT ,
341+ @pspo_sql NVARCHAR (MAX ) = N' SELECT @i_out = CONVERT(bit,dsc.value)
342+ FROM ' + QUOTENAME (@DatabaseName) + N' .sys.database_scoped_configurations dsc
343+ WHERE dsc.name = '' PARAMETER_SENSITIVE_PLAN_OPTIMIZATION'' ;' ,
344+ @pspo_params NVARCHAR (MAX ) = N ' @i_out INT OUTPUT' ;
345+
346+ EXEC sys .sp_executesql @pspo_sql, @pspo_params, @i_out = @pspo_out OUTPUT ;
347+
348+ SET @pspo_enabled = CASE WHEN @pspo_out = 1 THEN 1 ELSE 0 END ;
349+
350+ SET @msg = N ' Parameter Sensitive Plan Optimization ' + CASE @pspo_enabled
351+ WHEN 0 THEN N ' not enabled, skipping.'
352+ WHEN 1 THEN N ' enabled, will analyze.'
353+ END ;
354+ RAISERROR (@msg, 0 , 1 ) WITH NOWAIT ;
333355
334356/*
335357These are the temp tables we use
@@ -1033,10 +1055,33 @@ IF @MinimumExecutionCount IS NOT NULL
10331055
10341056-- You care about stored proc names
10351057IF @StoredProcName IS NOT NULL
1036- BEGIN
1037- RAISERROR (N ' Setting stored proc filter' , 0 , 1 ) WITH NOWAIT ;
1038- SET @sql_where + = N ' AND object_name(qsq.object_id, DB_ID(' + QUOTENAME (@DatabaseName, ' '' ' ) + N' )) = @sp_StoredProcName
1039- ' ;
1058+ BEGIN
1059+
1060+ IF (@pspo_enabled = 1 )
1061+ BEGIN
1062+ RAISERROR (N ' Setting stored proc filter, PSPO enabled' , 0 , 1 ) WITH NOWAIT ;
1063+ /* If PSPO is enabled, the object_id for a variant query would be 0. To include it, we check whether the object_id = 0 query
1064+ is a variant query, and whether it's parent query belongs to @sp_StoredProcName. */
1065+ SET @sql_where + = N ' AND (object_name(qsq.object_id, DB_ID(' + QUOTENAME (@DatabaseName, ' '' ' ) + N' )) = @sp_StoredProcName
1066+ OR (qsq.object_id = 0
1067+ AND EXISTS(
1068+ SELECT 1
1069+ FROM ' + QUOTENAME (@DatabaseName) + N' .sys.query_store_query_variant vr
1070+ JOIN ' + QUOTENAME (@DatabaseName) + N' .sys.query_store_query pqsq
1071+ ON pqsq.query_id = vr.parent_query_id
1072+ WHERE
1073+ vr.query_variant_query_id = qsq.query_id
1074+ AND object_name(pqsq.object_id, DB_ID(' + QUOTENAME (@DatabaseName, ' '' ' ) + N' )) = @sp_StoredProcName
1075+ )
1076+ ))
1077+ ' ;
1078+ END
1079+ ELSE
1080+ BEGIN
1081+ RAISERROR (N ' Setting stored proc filter' , 0 , 1 ) WITH NOWAIT ;
1082+ SET @sql_where + = N ' AND object_name(qsq.object_id, DB_ID(' + QUOTENAME (@DatabaseName, ' '' ' ) + N' )) = @sp_StoredProcName
1083+ ' ;
1084+ END
10401085 END ;
10411086
10421087-- I will always love you, but hopefully this query will eventually end
0 commit comments