-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsp_StatUpdate.sql
More file actions
8779 lines (8135 loc) · 430 KB
/
sp_StatUpdate.sql
File metadata and controls
8779 lines (8135 loc) · 430 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
/*
sp_StatUpdate v3 - Priority-Based Statistics Maintenance
Copyright (c) 2026 Community Contribution
https://github.com/nanoDBA/sp_StatUpdate
Purpose: Update statistics with DMV-based priority ordering and time limits.
Refreshes stale stats including those with NORECOMPUTE (flag preserved).
Based on: Ola Hallengren's IndexOptimize (MIT License)
https://ola.hallengren.com
License: MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Version: 3.0.2026.04.07 (Major.Minor.YYYY.MM.DD)
- Version logged to CommandLog ExtendedInfo on each run
- Query: ExtendedInfo.value('(/Parameters/Version)[1]', 'nvarchar(20)')
History: 3.0.2026.04.07 - v3 architecture: preset-first API, 33 input params (was 58),
+ 10 OUTPUT params. Absorbed 25 params into @i_ internal
variables controlled by presets. Table-driven validation,
6-phase staged discovery only (no fallback path), removed join
pattern grouping, removed global temp progress table, unified
mop-up filters. Full behavioral parity with v2.37.
Key Features:
- Preset-first API: DEFAULT, NIGHTLY, WEEKLY_FULL, OLTP_LIGHT, WAREHOUSE
- 6-phase staged discovery (only path, no legacy fallback)
- Queue-based parallelism for large databases
- Priority ordering (worst stats first)
- Incremental statistics support (ON PARTITIONS)
- RESAMPLE option for preserving sample rates
- Availability Group awareness (prevents write attempts on secondaries)
- Memory-optimized table handling
- Mop-up pass: broad sweep with remaining time budget
- Query Store integration: CPU, DURATION, READS, MEMORY_GRANT, TEMPDB_SPILLS,
PHYSICAL_READS, AVG_MEMORY, WAITS, AVG_CPU, EXECUTIONS
DROP-IN COMPATIBILITY with Ola Hallengren's SQL Server Maintenance Solution:
https://ola.hallengren.com
REQUIRED:
- dbo.CommandLog table (https://ola.hallengren.com/scripts/CommandLog.sql)
Used for all logging. Set @LogToTable = 'N' if you don't have it.
OPTIONAL (for @StatsInParallel = 'Y'):
- dbo.Queue table (https://ola.hallengren.com/scripts/Queue.sql)
- dbo.QueueStatistic table (auto-created on first parallel run)
NOT REQUIRED:
- dbo.CommandExecute - sp_StatUpdate handles its own command execution
Note: NORECOMPUTE flag is PRESERVED on update (not cleared).
To clear NORECOMPUTE, manually DROP + CREATE the statistic.
*/
IF OBJECT_ID(N'dbo.sp_StatUpdate', N'P') IS NULL
BEGIN
EXECUTE (N'CREATE PROCEDURE dbo.sp_StatUpdate AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_StatUpdate
(
/*
============================================================================
v3 SIMPLIFIED API
33 input parameters (was 58 in v2) + 10 OUTPUT parameters
25 input parameters absorbed into preset-controlled @i_ internal variables.
Explicit params always override preset defaults.
INPUT (33): @Statistics, @Preset, @Databases, @Tables, @ExcludeTables,
@ExcludeStatistics, @TargetNorecompute, @StaleHours, @QueryStore,
@TimeLimit, @StopByTime, @BatchLimit, @SortOrder, @MopUpPass,
@StatisticsSample, @MaxDOP, @ModificationThreshold,
@LongRunningThresholdMinutes, @LongRunningSamplePercent,
@QueryStoreTopPlans, @QueryStoreMinExecutions, @QueryStoreRecentHours,
@MaxAGRedoQueueMB, @MaxAGWaitMinutes, @MinTempdbFreeMB,
@MopUpMinRemainingSeconds, @LogToTable, @Execute, @WhatIfOutputTable,
@FailFast, @Debug, @StatsInParallel, @Help
OUTPUT (10): @Version, @VersionDate, @StatsFoundOut, @StatsProcessedOut,
@StatsSucceededOut, @StatsFailedOut, @StatsRemainingOut,
@DurationSecondsOut, @WarningsOut, @StopReasonOut
============================================================================
*/
/* MODE 1: DIRECT -- pass specific statistics (skips DMV discovery) */
@Statistics sysname = NULL, /* 'Schema.Table.Stat' or 'Table.Stat', comma-separated */
/* MODE 2: DISCOVERY -- DMV-based candidate selection */
@Preset nvarchar(20) = N'DEFAULT', /* DEFAULT, NIGHTLY, WEEKLY_FULL, OLTP_LIGHT, WAREHOUSE */
@Databases nvarchar(max) = NULL, /* NULL = current DB. SYSTEM_DATABASES, USER_DATABASES, ALL_DATABASES, wildcards (%), exclusions (-) */
@Tables nvarchar(max) = NULL, /* NULL = all tables, or comma-separated 'Schema.Table' */
@ExcludeTables nvarchar(max) = NULL, /* comma-separated patterns (supports %) */
@ExcludeStatistics nvarchar(max) = NULL, /* comma-separated patterns (supports %) */
@TargetNorecompute nvarchar(10) = N'BOTH', /* Y = only NORECOMPUTE, N = only regular, BOTH = all */
@StaleHours int = NULL, /* minimum hours since last update (replaces @DaysStaleThreshold + @HoursStaleThreshold) */
/* QUERY STORE -- single param replaces @QueryStorePriority + @QueryStoreMetric */
@QueryStore nvarchar(20) = NULL, /* OFF or metric name: CPU, DURATION, READS, EXECUTIONS, AVG_CPU, MEMORY_GRANT, TEMPDB_SPILLS, PHYSICAL_READS, AVG_MEMORY, WAITS. NULL = preset decides. */
/* EXECUTION CONTROL */
@TimeLimit integer = NULL, /* seconds. NULL = preset decides (DEFAULT=18000, NIGHTLY=3600, etc.) */
@StopByTime nvarchar(8) = NULL, /* absolute stop time: HHMM, HH:MM, HH:MM:SS. Overrides @TimeLimit. */
@BatchLimit integer = NULL, /* max stats per run */
@SortOrder nvarchar(50) = NULL, /* NULL = preset decides. MODIFICATION_COUNTER, DAYS_STALE, PAGE_COUNT, RANDOM, QUERY_STORE, FILTERED_DRIFT, AUTO_CREATED, ROWS */
@MopUpPass nvarchar(1) = NULL, /* Y/N. NULL = preset decides. Broad sweep after priority pass. */
@StatisticsSample integer = NULL, /* 1-100 (100=FULLSCAN), NULL = let SQL decide */
@MaxDOP integer = NULL, /* MAXDOP for UPDATE STATISTICS (SQL 2016 SP2+). NULL = server default */
@ModificationThreshold bigint = NULL, /* Override preset mod threshold floor (large tables). NULL = preset decides */
@LongRunningThresholdMinutes integer = NULL, /* Stats historically slower than this get forced sample rate. NULL = disabled */
@LongRunningSamplePercent integer = NULL, /* Sample percent for long-running stats (default preset: 10%). NULL = preset decides */
/* QUERY STORE TUNING */
@QueryStoreTopPlans integer = NULL, /* Limit Phase 6 XML plan parsing to top N plans. NULL = preset decides (default 500). */
@QueryStoreMinExecutions integer = NULL, /* Min plan executions for QS boost (default 100). NULL = preset decides. */
@QueryStoreRecentHours integer = NULL, /* Only consider QS plans from last N hours (default 168=7d). NULL = preset decides. */
/* AVAILABILITY GROUP & TEMPDB SAFETY */
@MaxAGRedoQueueMB integer = NULL, /* Pause if AG secondary redo queue exceeds this MB. NULL = disabled. */
@MaxAGWaitMinutes integer = NULL, /* Max minutes to wait for AG redo queue to drain (default 10). */
@MinTempdbFreeMB integer = NULL, /* Min free tempdb space in MB. NULL = disabled. */
/* MOP-UP TUNING */
@MopUpMinRemainingSeconds integer = NULL, /* Min seconds remaining to trigger mop-up. NULL = preset decides (default 60). */
/* LOGGING & OUTPUT */
@LogToTable nvarchar(1) = N'Y', /* Y = log to dbo.CommandLog, N = skip */
@Execute nvarchar(1) = N'Y', /* Y = execute, N = dry run */
@WhatIfOutputTable nvarchar(500) = NULL, /* table for commands when @Execute = N */
@FailFast bit = 0, /* 1 = abort on first error */
@Debug bit = 0, /* 1 = verbose output */
/* PARALLEL EXECUTION */
@StatsInParallel nvarchar(1) = N'N', /* Y = queue-based parallel processing */
/* HELP & VERSION */
@Help nvarchar(50) = N'0', /* 1 = show help */
@Version varchar(20) = NULL OUTPUT,
@VersionDate datetime = NULL OUTPUT,
/* SUMMARY OUTPUT */
@StatsFoundOut integer = NULL OUTPUT,
@StatsProcessedOut integer = NULL OUTPUT,
@StatsSucceededOut integer = NULL OUTPUT,
@StatsFailedOut integer = NULL OUTPUT,
@StatsRemainingOut integer = NULL OUTPUT,
@DurationSecondsOut integer = NULL OUTPUT,
@WarningsOut nvarchar(max) = NULL OUTPUT,
@StopReasonOut nvarchar(50) = NULL OUTPUT
)
WITH RECOMPILE
AS
BEGIN
/*#region 01-INIT: SET options, version constants */
SET NOCOUNT ON;
SET XACT_ABORT ON;
SET ARITHABORT ON;
SET NUMERIC_ROUNDABORT OFF;
DECLARE
@procedure_version varchar(20) = '3.0.2026.04.07',
@procedure_version_date datetime = '20260407',
@procedure_name sysname = OBJECT_NAME(@@PROCID),
@procedure_schema sysname = OBJECT_SCHEMA_NAME(@@PROCID);
SELECT
@Version = @procedure_version,
@VersionDate = @procedure_version_date;
/*#endregion 01-INIT */
/*#region 02-HELP: Condensed table-driven help */
IF @Help IN (N'1', N'Y')
BEGIN
/* RS 1: Introduction */
SELECT introduction = line_text
FROM (VALUES
(1, N'sp_StatUpdate v3 -- Priority-Based Statistics Maintenance'),
(2, N'Version: ' + @procedure_version + N' (' + CONVERT(nvarchar(10), @procedure_version_date, 120) + N')'),
(3, N'https://github.com/nanoDBA/sp_StatUpdate'),
(4, N''),
(5, N'v3 simplifies the API from 58 to 33 input parameters (+ 10 OUTPUT). Use @Preset'),
(6, N'for common configurations, override individual settings as needed.'),
(7, N''),
(8, N'Quick start:'),
(9, N' EXEC sp_StatUpdate @Databases = N''USER_DATABASES''; -- DEFAULT preset'),
(10, N' EXEC sp_StatUpdate @Preset = N''NIGHTLY'', @Databases = N''USER_DATABASES''; -- 1hr, QS-prioritized'),
(11, N' EXEC sp_StatUpdate @Preset = N''WEEKLY_FULL'', @Execute = N''N''; -- dry run'),
(12, N' EXEC sp_StatUpdate @QueryStore = N''CPU'', @MopUpPass = N''Y''; -- QS + mop-up'),
(13, N''),
(14, N'Run sp_StatUpdate_Diag for post-run diagnostics and recommendations.')
) AS h(sort_order, line_text)
ORDER BY h.sort_order;
/* RS 2: Preset definitions */
SELECT
preset_name = p.preset_name,
time_limit = p.time_limit,
sort_order = p.sort_order,
query_store = p.query_store,
mop_up = p.mop_up,
sample = p.sample_pct,
description = p.description
FROM (VALUES
(N'DEFAULT', N'18000 (5h)', N'MODIFICATION_COUNTER', N'OFF', N'N', N'auto', N'Balanced default. Tiered thresholds, 5h limit.'),
(N'NIGHTLY', N'3600 (1h)', N'QUERY_STORE', N'CPU', N'Y', N'auto', N'QS-prioritized nightly job with mop-up.'),
(N'WEEKLY_FULL', N'14400 (4h)', N'QUERY_STORE', N'CPU', N'Y', N'100', N'Comprehensive weekly: FULLSCAN + lower thresholds.'),
(N'OLTP_LIGHT', N'1800 (30m)', N'MODIFICATION_COUNTER', N'OFF', N'N', N'auto', N'Low-impact OLTP: high threshold, inter-stat delay.'),
(N'WAREHOUSE', N'unlimited', N'ROWS', N'OFF', N'N', N'100', N'Data warehouse: FULLSCAN, no time limit.')
) AS p(preset_name, time_limit, sort_order, query_store, mop_up, sample_pct, description);
/* RS 3: Parameter reference */
SELECT
parameter = r.parameter,
[type] = r.data_type,
[default] = r.default_value,
description = r.description
FROM (VALUES
(N'@Statistics', N'sysname', N'NULL', N'Direct mode: Schema.Table.Stat (comma-separated)'),
(N'@Preset', N'nvarchar(20)', N'DEFAULT', N'DEFAULT, NIGHTLY, WEEKLY_FULL, OLTP_LIGHT, WAREHOUSE'),
(N'@Databases', N'nvarchar(max)', N'NULL', N'NULL=current DB. USER_DATABASES, ALL_DATABASES, wildcards, exclusions'),
(N'@Tables', N'nvarchar(max)', N'NULL', N'NULL=all tables, or Schema.Table list'),
(N'@ExcludeTables', N'nvarchar(max)', N'NULL', N'Patterns to exclude (supports %)'),
(N'@ExcludeStatistics', N'nvarchar(max)', N'NULL', N'Patterns to exclude (supports %)'),
(N'@TargetNorecompute', N'nvarchar(10)', N'BOTH', N'BOTH=all stats (default), Y=NORECOMPUTE only, N=regular only'),
(N'@StaleHours', N'int', N'NULL', N'Min hours since last update'),
(N'@QueryStore', N'nvarchar(20)', N'NULL', N'OFF or metric: CPU, DURATION, READS, EXECUTIONS, etc.'),
(N'@TimeLimit', N'integer', N'NULL', N'Seconds. NULL=preset decides'),
(N'@StopByTime', N'nvarchar(8)', N'NULL', N'Absolute stop: HHMM or HH:MM:SS. Overrides @TimeLimit'),
(N'@BatchLimit', N'integer', N'NULL', N'Max stats per run'),
(N'@SortOrder', N'nvarchar(50)', N'NULL', N'NULL=preset. MODIFICATION_COUNTER, QUERY_STORE, etc.'),
(N'@MopUpPass', N'nvarchar(1)', N'NULL', N'Y/N. Broad sweep with remaining time'),
(N'@StatisticsSample', N'integer', N'NULL', N'1-100 (100=FULLSCAN), NULL=auto'),
(N'@MaxDOP', N'integer', N'NULL', N'MAXDOP for UPDATE STATISTICS'),
(N'@ModificationThreshold', N'bigint', N'NULL', N'Override preset mod threshold floor. NULL=preset decides'),
(N'@LongRunningThresholdMinutes', N'integer', N'NULL', N'Stats slower than this get forced sample. NULL=disabled'),
(N'@LongRunningSamplePercent', N'integer', N'NULL', N'Sample pct for long-running stats. NULL=preset (10%)'),
(N'@QueryStoreTopPlans', N'integer', N'NULL', N'Limit Phase 6 XML plan parsing. NULL=preset (500)'),
(N'@QueryStoreMinExecutions', N'integer', N'NULL', N'Min plan executions for QS boost. NULL=preset (100)'),
(N'@QueryStoreRecentHours', N'integer', N'NULL', N'QS plans from last N hours. NULL=preset (168=7d)'),
(N'@MaxAGRedoQueueMB', N'integer', N'NULL', N'Pause if AG redo queue exceeds MB. NULL=disabled'),
(N'@MaxAGWaitMinutes', N'integer', N'NULL', N'Max minutes to wait for AG redo drain (default 10)'),
(N'@MinTempdbFreeMB', N'integer', N'NULL', N'Min free tempdb MB. NULL=disabled'),
(N'@MopUpMinRemainingSeconds', N'integer', N'NULL', N'Min seconds remaining to trigger mop-up. NULL=preset (60)'),
(N'@LogToTable', N'nvarchar(1)', N'Y', N'Log to dbo.CommandLog'),
(N'@Execute', N'nvarchar(1)', N'Y', N'Y=execute, N=dry run'),
(N'@WhatIfOutputTable', N'nvarchar(500)', N'NULL', N'Table for dry-run commands'),
(N'@FailFast', N'bit', N'0', N'Abort on first error'),
(N'@Debug', N'bit', N'0', N'Verbose output'),
(N'@StatsInParallel', N'nvarchar(1)', N'N', N'Queue-based parallel processing'),
(N'@Help', N'nvarchar(50)', N'0', N'1 = show this help')
) AS r(parameter, data_type, default_value, description);
/* RS 4: Help topics */
SELECT
topic = t.topic,
detail = t.detail
FROM (VALUES
(N'QUICK START', N'Use @Preset for a pre-tuned config. Override individual params as needed. @Execute=N for dry run.'),
(N'PRESETS', N'DEFAULT=balanced, NIGHTLY=1h+QS+mop-up, WEEKLY_FULL=4h+FULLSCAN, OLTP_LIGHT=30m+high-thresh, WAREHOUSE=unlimited+FULLSCAN.'),
(N'PARALLEL', N'@StatsInParallel=Y. Requires dbo.Queue + dbo.QueueStatistic (auto-created). Run same EXEC from multiple Agent steps.'),
(N'QUERY STORE', N'@QueryStore=CPU/DURATION/READS/etc. to prioritize stats on high-workload tables. OFF to disable.'),
(N'MOP-UP', N'@MopUpPass=Y: after priority pass, sweep any stat with modification_counter>0. Needs @TimeLimit + @LogToTable=Y.'),
(N'DIRECT MODE', N'@Statistics=''Schema.Table.Stat'' for ad-hoc updates. Skips discovery. Comma-separate for multiple.'),
(N'STALE HOURS', N'@StaleHours=48 means skip stats updated within 48 hours. Replaces v2 @DaysStaleThreshold/@HoursStaleThreshold.'),
(N'SCHEDULING', N'SQL Agent job with @Preset=NIGHTLY + @StopByTime=0500 for a 5 AM deadline. Use @MopUpPass=Y for thorough coverage.'),
(N'NORECOMPUTE', N'NORECOMPUTE flag is PRESERVED on update (not cleared). To clear: manually DROP+CREATE the statistic.'),
(N'COMMANDLOG', N'Requires dbo.CommandLog from https://ola.hallengren.com/scripts/CommandLog.sql. Set @LogToTable=N if not installed.'),
(N'DIAGNOSTICS', N'Run sp_StatUpdate_Diag after for automated analysis. @ExpertMode=1 for full detail, 0 for dashboard only.'),
(N'VERSION', N'v3.0 -- simplified API (33 input + 10 OUTPUT vs 58 input + 10 OUTPUT in v2). Full behavioral parity with v2.37. Preset-first design.')
) AS t(topic, detail);
RETURN;
END;
/*#endregion 02-HELP */
/*#region 03-SETUP: Re-entrancy, variables, guards, presets, validation */
/*#region 03A-TRANCOUNT: Transaction guard + StatUpdateLock re-entrancy */
/*
Check transaction count BEFORE acquiring re-entrancy lock -- UPDATE STATISTICS
acquires Sch-M locks that escalate unpredictably inside a caller's transaction.
Must precede lock acquisition to avoid masking the real error.
*/
IF @@TRANCOUNT <> 0
BEGIN
RAISERROR(N'The transaction count is not 0. sp_StatUpdate must not be called within an open transaction.', 16, 1) WITH NOWAIT;
SET @StopReasonOut = N'PARAMETER_ERROR';
SET @StatsFoundOut = 0;
SET @StatsProcessedOut = 0;
SET @StatsSucceededOut = 0;
SET @StatsFailedOut = 0;
SET @StatsRemainingOut = 0;
SET @DurationSecondsOut = 0;
SELECT
Status = N'ERROR', StatusMessage = N'Open transaction detected.',
StatsFound = 0, StatsProcessed = 0, StatsSucceeded = 0, StatsFailed = 0,
StatsToctou = 0, StatsSkipped = 0, StatsRemaining = 0,
DatabasesProcessed = 0, DurationSeconds = 0,
StopReason = N'PARAMETER_ERROR', RunLabel = CONVERT(nvarchar(100), NULL),
Version = @procedure_version;
RETURN 1;
END;
/*
============================================================================
RE-ENTRANCY GUARD (queue-table pattern, bd -j9d)
Prevents concurrent non-parallel runs from corrupting shared state
(orphan cleanup, progress tables, CommandLog bracketing).
Uses a row in dbo.StatUpdateLock with (SessionID, LoginTime) liveness
tuple instead of sp_getapplock. Dead holders are auto-reclaimed via
sys.dm_exec_sessions -- no ALREADY_RUNNING cascade when sessions die.
Parallel mode workers skip this guard -- they coordinate via dbo.Queue +
dbo.QueueStatistic.
============================================================================
*/
IF NOT EXISTS (
SELECT 1 FROM sys.objects AS o
JOIN sys.schemas AS s ON s.schema_id = o.schema_id
WHERE o.type = N'U' AND s.name = N'dbo' AND o.name = N'StatUpdateLock'
)
BEGIN
CREATE TABLE dbo.StatUpdateLock (
Resource sysname NOT NULL,
SessionID smallint NOT NULL,
LoginTime datetime NOT NULL,
AcquiredAt datetime2(3) NOT NULL DEFAULT SYSDATETIME(),
CONSTRAINT PK_StatUpdateLock PRIMARY KEY CLUSTERED (Resource)
);
END;
IF @StatsInParallel = N'N'
BEGIN
DECLARE @my_login_time datetime =
(SELECT s.login_time FROM sys.dm_exec_sessions AS s WHERE s.session_id = @@SPID);
DECLARE @existing_sid smallint, @existing_lt datetime;
BEGIN TRANSACTION;
SELECT @existing_sid = SessionID, @existing_lt = LoginTime
FROM dbo.StatUpdateLock WITH (UPDLOCK, HOLDLOCK)
WHERE Resource = N'sp_StatUpdate';
IF @existing_sid IS NULL
BEGIN
INSERT INTO dbo.StatUpdateLock (Resource, SessionID, LoginTime)
VALUES (N'sp_StatUpdate', @@SPID, @my_login_time);
END
ELSE IF EXISTS (
SELECT 1 FROM sys.dm_exec_sessions
WHERE session_id = @existing_sid AND login_time = @existing_lt
)
BEGIN
COMMIT TRANSACTION;
RAISERROR(N'Another instance of sp_StatUpdate is already running (non-parallel mode). Use @StatsInParallel=''Y'' for concurrent execution.', 16, 1);
SET @StopReasonOut = N'ALREADY_RUNNING';
SET @StatsFoundOut = 0;
SET @StatsProcessedOut = 0;
SET @StatsSucceededOut = 0;
SET @StatsFailedOut = 0;
SET @StatsRemainingOut = 0;
SET @DurationSecondsOut = 0;
SELECT
Status = N'ERROR', StatusMessage = N'Another instance already running.',
StatsFound = 0, StatsProcessed = 0, StatsSucceeded = 0, StatsFailed = 0,
StatsToctou = 0, StatsSkipped = 0, StatsRemaining = 0,
DatabasesProcessed = 0, DurationSeconds = 0,
StopReason = N'ALREADY_RUNNING', RunLabel = CONVERT(nvarchar(100), NULL),
Version = @procedure_version;
RETURN;
END
ELSE
BEGIN
/* Dead holder -- reclaim */
UPDATE dbo.StatUpdateLock
SET SessionID = @@SPID, LoginTime = @my_login_time, AcquiredAt = SYSDATETIME()
WHERE Resource = N'sp_StatUpdate';
END;
COMMIT TRANSACTION;
END;
/*#endregion 03A-TRANCOUNT */
/*#region 03B-VARIABLES: Version detection, trace flags, table variables, temp tables */
/*
============================================================================
VARIABLE DECLARATIONS
============================================================================
*/
DECLARE
@start_time datetime2(7) = SYSDATETIME(),
@empty_line nvarchar(max) = N'',
@error_number integer = 0,
@return_code integer = 0,
/*
Capture original LOCK_TIMEOUT to restore after stat updates (P1 #23 v1.9)
@@LOCK_TIMEOUT returns -1 for infinite wait, or timeout in milliseconds
*/
@original_lock_timeout integer = @@LOCK_TIMEOUT;
/*
SQL Server version detection
Major version: 13 = 2016, 14 = 2017, 15 = 2019, 16 = 2022, 17 = 2025
Build number used for feature detection (e.g., PERSIST_SAMPLE_PERCENT, MAXDOP in UPDATE STATISTICS)
Future versions (>= 17) inherit SQL 2022 feature set -- all >= comparisons forward-compatible.
*/
DECLARE
@sql_version numeric(18, 10) =
CONVERT
(
numeric(18, 10),
LEFT
(
CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion')),
CHARINDEX
(
N'.',
CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion'))
) - 1
) +
N'.' +
REPLACE
(
RIGHT
(
CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion')),
LEN(CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion'))) -
CHARINDEX
(
N'.',
CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion'))
)
),
N'.',
N''
)
),
@sql_major_version integer =
CONVERT
(
integer,
LEFT
(
CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion')),
CHARINDEX
(
N'.',
CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion'))
) - 1
)
),
@sql_build_number integer =
CONVERT
(
integer,
PARSENAME(CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion')), 2)
),
/*
Feature availability flags based on SQL Server version/build:
- PERSIST_SAMPLE_PERCENT: SQL 2016 SP1 CU4+ (build 4446+) or SQL 2017+
- MAXDOP in UPDATE STATISTICS: SQL 2016 SP2+ (build 5026+) or SQL 2017 CU3+ (build 3015+)
*/
@supports_persist_sample bit = 0,
@supports_maxdop_stats bit = 0,
/* SQL 2022+ feature detection (includes SQL 2025/v17+) */
@supports_auto_drop bit = 0;
/* Set AUTO_DROP support flag (SQL 2022+ / v16+) */
IF @sql_major_version >= 16
SET @supports_auto_drop = 1;
/*
Phase 1 Environment Detection (v2.0)
Trace flags affecting statistics behavior - detected once at startup.
*/
DECLARE
@trace_flags table
(
TraceFlag int NOT NULL,
Status bit NOT NULL,
Global bit NOT NULL,
Session bit NOT NULL
);
DECLARE
@tf_2371_active bit = 0, /* Dynamic thresholds (built-in for SQL 2016+ CL 130+) */
@tf_2389_active bit = 0, /* Ascending key detection (legacy) */
@tf_2390_active bit = 0, /* Descending key detection (legacy) */
@tf_4139_active bit = 0, /* Universal histogram amendment (modern) */
@tf_9481_active bit = 0, /* Force legacy CE */
@tf_warnings nvarchar(max) = N'';
/* Query active trace flags */
INSERT INTO @trace_flags (TraceFlag, Status, Global, Session)
EXEC (N'DBCC TRACESTATUS(-1) WITH NO_INFOMSGS');
/* Check for statistics-relevant trace flags */
SELECT
@tf_2371_active = MAX(CASE WHEN TraceFlag = 2371 AND Status = 1 THEN 1 ELSE 0 END),
@tf_2389_active = MAX(CASE WHEN TraceFlag = 2389 AND Status = 1 THEN 1 ELSE 0 END),
@tf_2390_active = MAX(CASE WHEN TraceFlag = 2390 AND Status = 1 THEN 1 ELSE 0 END),
@tf_4139_active = MAX(CASE WHEN TraceFlag = 4139 AND Status = 1 THEN 1 ELSE 0 END),
@tf_9481_active = MAX(CASE WHEN TraceFlag = 9481 AND Status = 1 THEN 1 ELSE 0 END)
FROM @trace_flags;
/* Build trace flag warnings for debug output */
IF @tf_2371_active = 1 AND @sql_major_version >= 13
SET @tf_warnings = @tf_warnings + N'TF 2371 unnecessary (built-in for SQL 2016+ CL 130+); ';
IF @tf_2389_active = 1 OR @tf_2390_active = 1
SET @tf_warnings = @tf_warnings + N'TF 2389/2390 are legacy ascending key flags - consider TF 4139 instead; ';
IF @tf_4139_active = 1
SET @tf_warnings = @tf_warnings + N'TF 4139 active (histogram amendment for ascending keys); ';
IF @tf_9481_active = 1
SET @tf_warnings = @tf_warnings + N'TF 9481 forces legacy CE 70 globally - consider db-scoped config instead; ';
/*
Error collection table (show all errors at once)
*/
DECLARE
@errors table
(
id integer IDENTITY(1, 1) PRIMARY KEY,
error_message nvarchar(max) NOT NULL,
error_severity integer NOT NULL
);
/*
Selected databases tables (Ola Hallengren pattern)
Supports: SYSTEM_DATABASES, USER_DATABASES, ALL_DATABASES,
AVAILABILITY_GROUP_DATABASES, wildcards (%), exclusions (-)
*/
DECLARE
@SelectedDatabases table
(
DatabaseItem nvarchar(max),
DatabaseType char(1), /* S=System, U=User, NULL=Any */
AvailabilityGroup bit, /* 1=AG databases only */
StartPosition integer,
Selected bit /* 1=Include, 0=Exclude */
);
DECLARE
@tmpDatabases table
(
ID integer IDENTITY(1, 1) PRIMARY KEY,
DatabaseName sysname NOT NULL,
DatabaseType char(1), /* S=System, U=User */
AvailabilityGroup bit,
Selected bit NOT NULL DEFAULT 0,
Completed bit NOT NULL DEFAULT 0
);
DECLARE
@CurrentDatabaseID integer = NULL,
@CurrentDatabaseName sysname = NULL,
@database_count integer = 0;
/*
Current item variables
*/
DECLARE
@current_database sysname = NULL,
@current_schema_name sysname = NULL,
@current_table_name sysname = NULL,
@current_stat_name sysname = NULL,
@current_object_id integer = NULL,
@current_stats_id integer = NULL,
@current_no_recompute bit = NULL,
@current_is_incremental bit = NULL,
@current_is_memory_optimized bit = NULL,
@current_is_heap bit = NULL,
@current_auto_created bit = NULL,
@current_modification_counter bigint = NULL,
@current_row_count bigint = NULL,
@current_days_stale integer = NULL,
@current_page_count bigint = NULL,
@current_persisted_sample_percent float = NULL,
@absolute_sampled_rows bigint = NULL, /*P1c: computed actual sampled rows from @current_row_count * @current_persisted_sample_percent*/
@p246_pct int = NULL,
@p246_msg nvarchar(500) = NULL,
@current_histogram_steps int = NULL,
@current_partition_number integer = NULL,
@current_forwarded_records bigint = NULL,
/* Replication and temporal table awareness */
@current_is_published bit = NULL,
@current_is_tracked_by_cdc bit = NULL,
@current_temporal_type tinyint = NULL,
/* Filtered statistics metadata */
@current_has_filter bit = NULL,
@current_filter_definition nvarchar(max) = NULL,
@current_unfiltered_rows bigint = NULL,
@current_filtered_drift_ratio float = NULL,
/* Query Store priority metadata */
@current_qs_plan_count integer = NULL,
@current_qs_total_executions bigint = NULL,
@current_qs_total_cpu_ms bigint = NULL,
@current_qs_total_duration_ms bigint = NULL,
@current_qs_total_logical_reads bigint = NULL,
@current_qs_total_memory_grant_kb bigint = NULL,
@current_qs_total_tempdb_pages bigint = NULL,
@current_qs_total_physical_reads bigint = NULL,
@current_qs_total_logical_writes bigint = NULL,
@current_qs_total_wait_time_ms bigint = NULL,
@current_qs_max_dop smallint = NULL,
@current_qs_active_feedback_count int = NULL,
@current_qs_last_execution datetime2(3) = NULL,
@current_qs_priority_boost bigint = NULL;
/*
TOCTOU check variables (verify stat still exists before execution)
*/
DECLARE
@toctou_sql nvarchar(500) = N'',
@toctou_exists int = 0;
/*
Command building
*/
DECLARE
@current_command nvarchar(max) = N'',
@current_command_type nvarchar(60) = N'UPDATE_STATISTICS',
@current_start_time datetime2(7) = NULL,
@current_end_time datetime2(7) = NULL,
@current_error_number integer = NULL,
@current_error_message nvarchar(max) = NULL,
@current_extended_info xml = NULL,
@current_commandlog_id integer = NULL;
/*
Output message helpers
*/
DECLARE
@norecompute_display nvarchar(20) = N'',
@duration_ms integer = 0,
@progress_msg nvarchar(500) = N'',
@persisted_pct_msg integer = 0,
@iteration_time datetime2(7) = NULL, /*Captured once per loop iteration for consistent timing*/
@log_error_msg nvarchar(4000) = NULL; /*For TRY/CATCH - truncate at assignment to leave room for prefix*/
/* P3e (v2.4): ETR (Estimated Time Remaining) tracking variables */
DECLARE
@etr_total_ms bigint = 0, /* Running total ms across all completed stats */
@etr_completed int = 0, /* Count of stats completed (successful executions) */
@etr_suffix nvarchar(50) = N'', /* ETR display suffix appended to Complete message */
@etr_avg_ms bigint = 0, /* Average ms per stat for current run */
@etr_remaining_count int = 0, /* Stats remaining in queue */
@etr_ms bigint = 0, /* Estimated remaining ms */
@etr_display nvarchar(20) = N''; /* Human-readable ETR string (~Xh Ym, ~Xm, ~Xs) */
/*
Run identification for tracking completion
*/
DECLARE
@run_label nvarchar(100) = CONVERT(nvarchar(128), SERVERPROPERTY(N'ServerName'))
+ N'_' + CONVERT(nvarchar(20), @start_time, 112)
+ N'_' + REPLACE(CONVERT(nvarchar(20), @start_time, 108), N':', N''), /* #429 */
@stop_reason nvarchar(50) = NULL,
@commandlog_exists bit = CASE WHEN OBJECT_ID(N'dbo.CommandLog', N'U') IS NOT NULL THEN 1 ELSE 0 END,
@commandlog_3part nvarchar(300) = QUOTENAME(DB_NAME()) + N'.dbo.CommandLog', /* v2.26: 3-part name for mop-up dynamic SQL after USE <userdb> */
@mop_up_done bit = 0, /* v2.24: prevents mop-up re-entry after GOTO */
@in_mop_up bit = 0, /* v2.24: set during mop-up pass for QualifyReason tagging */
@mop_up_stats_found int = 0, /* v2.24: mop-up candidates discovered */
@mop_up_stats_processed int = 0, /* v2.24: mop-up stats processed (for summary XML) */
@mop_lock_result int = NULL, /* v2.24: parallel mop-up app lock result */
@mop_lock_resource nvarchar(255) = NULL; /* v2.24: parallel mop-up app lock name */
/*
Counters
*/
DECLARE
@stats_processed integer = 0,
@stats_succeeded integer = 0,
@stats_failed integer = 0,
@stats_toctou integer = 0,
@stats_skipped integer = 0,
@consecutive_failures integer = 0,
@total_pages_processed bigint = 0, /* v2.24: accumulated page count for volume reporting */
@warnings nvarchar(max) = N''; /* Collected warnings for @WarningsOut OUTPUT */
/*
Queue-based parallel processing variables
*/
DECLARE
@queue_id integer = NULL,
@queue_start_time datetime2(7) = NULL,
@parameters_string nvarchar(max) = N'',
@claimed_work bit = 0,
/*
Currently claimed table (parallel mode only).
Worker claims one table at a time, processes all its stats, then claims next.
*/
@claimed_table_database sysname = NULL,
@claimed_table_schema sysname = NULL,
@claimed_table_name sysname = NULL,
@claimed_table_object_id integer = NULL,
@claimed_table_stats_updated integer = 0,
@claimed_table_stats_failed integer = 0,
@claimed_table_stats_skipped integer = 0;
/*
Availability Group variables
*/
DECLARE
@is_ag_secondary bit = 0,
@ag_role_desc nvarchar(60) = NULL;
/*
AG redo queue monitoring variables (v2.7, #18)
*/
DECLARE
@ag_redo_queue_mb decimal(10, 2) = NULL,
@ag_wait_start datetime2(7) = NULL,
@ag_is_primary bit = 0,
@ag_redo_initial_mb bigint = NULL,
@ag_wait_msg nvarchar(500) = N'',
@ag_recovered_msg nvarchar(500) = N'';
/*
Tempdb pressure monitoring variables (v2.7, #34)
*/
DECLARE
@tempdb_free_mb bigint = NULL,
@tempdb_msg nvarchar(500) = N'';
/*
Long-running stats table (for adaptive sampling)
Stores stats that historically took longer than @LongRunningThresholdMinutes
*/
DECLARE @long_running_stats TABLE
(
database_name sysname NOT NULL,
schema_name sysname NOT NULL,
table_name sysname NOT NULL,
stat_name sysname NOT NULL,
max_duration_minutes int NOT NULL,
last_occurrence datetime2(7) NOT NULL,
occurrence_count int NOT NULL DEFAULT 1,
PRIMARY KEY NONCLUSTERED (database_name, schema_name, table_name, stat_name)
);
/*
============================================================================
TEMP TABLE FOR STATS TO PROCESS
============================================================================
*/
CREATE TABLE
#stats_to_process
(
id integer IDENTITY(1, 1) PRIMARY KEY,
database_name sysname NOT NULL,
schema_name sysname NOT NULL,
table_name sysname NOT NULL,
stat_name sysname NOT NULL,
object_id integer NOT NULL,
stats_id integer NOT NULL,
no_recompute bit NOT NULL DEFAULT 0,
is_incremental bit NOT NULL DEFAULT 0,
is_memory_optimized bit NOT NULL DEFAULT 0,
is_heap bit NOT NULL DEFAULT 0,
auto_created bit NOT NULL DEFAULT 0,
/* Table metadata for replication/CDC/temporal awareness */
is_published bit NOT NULL DEFAULT 0, /*transactional replication*/
is_tracked_by_cdc bit NOT NULL DEFAULT 0, /*Change Data Capture*/
temporal_type tinyint NOT NULL DEFAULT 0, /*0=none, 1=history, 2=system-versioned*/
modification_counter bigint NOT NULL DEFAULT 0,
row_count bigint NOT NULL DEFAULT 0,
days_stale integer NOT NULL DEFAULT 0,
page_count bigint NOT NULL DEFAULT 0,
partition_number integer NULL,
persisted_sample_percent float NULL, /*existing persisted sample (warn if overriding)*/
histogram_steps int NULL, /*number of histogram steps for diagnostic insight*/
/* Filtered statistics metadata */
has_filter bit NOT NULL DEFAULT 0,
filter_definition nvarchar(max) NULL,
unfiltered_rows bigint NULL, /*total rows in table, vs rows matching filter*/
filtered_drift_ratio AS /*computed: unfiltered_rows / NULLIF(row_count, 0) - measures selectivity drift*/
CASE WHEN row_count > 0 AND unfiltered_rows IS NOT NULL
THEN CONVERT(float, unfiltered_rows) / row_count
ELSE NULL
END,
/* Query Store priority metadata */
qs_plan_count integer NULL, /*distinct plans referencing this stat*/
qs_total_executions bigint NULL, /*total executions of plans using stat*/
qs_total_cpu_ms bigint NULL, /*total CPU time in ms (avg_cpu_time * count_executions / 1000)*/
qs_total_duration_ms bigint NULL, /*total elapsed time in ms*/
qs_total_logical_reads bigint NULL, /*total logical I/O reads*/
qs_total_memory_grant_kb bigint NULL, /*total memory grant KB (avg_query_max_used_memory * 8KB * executions)*/
qs_total_tempdb_pages bigint NULL, /*total tempdb pages (avg_tempdb_space_used * executions, SQL 2017+)*/
qs_total_physical_reads bigint NULL, /*total physical I/O reads (avg_num_physical_io_reads * executions, SQL 2017+)*/
qs_total_logical_writes bigint NULL, /*total logical write pages (avg_logical_io_writes * executions, diagnostic only)*/
qs_total_wait_time_ms bigint NULL, /*total stats-relevant wait time ms (BufferIO+Memory+SortAndTempDb from sys.query_store_wait_stats, SQL 2017+)*/
qs_max_dop smallint NULL, /*maximum observed DOP (last_dop, diagnostic only)*/
qs_active_feedback_count int NULL, /*SQL 2022+: count of active plan feedback entries (CE/grant/DOP)*/
qs_last_execution datetime2(3) NULL, /*most recent plan execution*/
qs_priority_boost bigint NOT NULL DEFAULT 0, /*calculated boost for QS stats*/
priority integer NOT NULL DEFAULT 0,
processed bit NOT NULL DEFAULT 0
);
/*
Index for efficient "get next unprocessed stat" query pattern:
WHERE processed = 0 ORDER BY priority
*/
CREATE NONCLUSTERED INDEX
IX_stats_to_process_processed_priority
ON #stats_to_process
(processed, priority)
INCLUDE
(database_name, schema_name, table_name, stat_name);
/*#endregion 03B-VARIABLES */
/*#region 03C-PREREQS: Version check, SET options, CommandLog, Queue auto-create, AG, Azure, RCSI */
/*
============================================================================
CORE REQUIREMENTS CHECKS
============================================================================
*/
/*
Check SQL Server version (STRING_SPLIT requires 2016+)
*/
IF @sql_version < 13
BEGIN
INSERT INTO
@errors
(
error_message,
error_severity
)
SELECT
error_message =
N'sp_StatUpdate requires SQL Server 2016 or later (STRING_SPLIT dependency). Current version: ' +
CONVERT(nvarchar(128), SERVERPROPERTY(N'ProductVersion')),
error_severity = 16;
END;
/*
Set feature availability flags based on SQL Server version/build
Reference: Microsoft Tiger Toolbox usp_AdaptiveIndexDefrag version detection
*/
SELECT
@supports_persist_sample =
CASE
WHEN @sql_major_version >= 14 THEN 1 /* SQL 2017+ */
WHEN @sql_major_version = 13 AND @sql_build_number >= 4446 THEN 1 /* SQL 2016 SP1 CU4+ */
ELSE 0
END,
@supports_maxdop_stats =
CASE
WHEN @sql_major_version >= 15 THEN 1 /* SQL 2019+ */
WHEN @sql_major_version = 14 AND @sql_build_number >= 3015 THEN 1 /* SQL 2017 CU3+ (14.0.3015.0, KB4041809) */
WHEN @sql_major_version = 13 AND @sql_build_number >= 5026 THEN 1 /* SQL 2016 SP2 RTM+ (13.0.5026.0, KB4041809) -- NOT SP1 */
/* NOTE: SQL 2016 SP1 (13.0.4001) and below do NOT support MAXDOP in UPDATE STATISTICS.
The feature was first shipped in SQL 2016 SP2 RTM (build 13.0.5026.0).
KB4041809: https://support.microsoft.com/kb/4041809 */
ELSE 0
END;
/*
Enforce SET options required by UPDATE STATISTICS on indexed views / computed columns.
Error 1934 fires when these are off (common via JDBC, linked servers, legacy ODBC).
Proactively SET them here -- values revert automatically when the proc returns.
ANSI_NULLS is captured at proc CREATE time (preamble), so only ANSI_WARNINGS
and ARITHABORT need runtime enforcement.
*/
IF SESSIONPROPERTY(N'ANSI_WARNINGS') <> 1
BEGIN
SET ANSI_WARNINGS ON;
RAISERROR(N'Note: SET ANSI_WARNINGS ON (was OFF, required for UPDATE STATISTICS)', 10, 1) WITH NOWAIT;
END;
IF SESSIONPROPERTY(N'ARITHABORT') <> 1
BEGIN
SET ARITHABORT ON;
RAISERROR(N'Note: SET ARITHABORT ON (was OFF, required for UPDATE STATISTICS)', 10, 1) WITH NOWAIT;
END;
/*
Check CommandLog exists if logging enabled
*/
IF @LogToTable = N'Y'
AND NOT EXISTS
(
SELECT
1
FROM sys.objects AS o
JOIN sys.schemas AS s
ON s.schema_id = o.schema_id
WHERE o.type = N'U'
AND s.name = N'dbo'
AND o.name = N'CommandLog'
)
BEGIN
INSERT INTO
@errors
(
error_message,
error_severity
)
SELECT
error_message =
N'The table dbo.CommandLog does not exist. Set @LogToTable = N''N'' or create the table from https://ola.hallengren.com/scripts/CommandLog.sql',
error_severity = 16;
END;
/*
v2.3: Check CommandLog schema compatibility when logging is enabled.
Non-blocking warning if expected columns are missing.
Required columns: CommandType, DatabaseName, SchemaName, ObjectName, StatisticName, ExtendedInfo.
*/
IF @LogToTable = N'Y'
AND @commandlog_exists = 1
BEGIN
DECLARE @commandlog_missing_cols nvarchar(max) = N'';
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.CommandLog') AND name = N'CommandType')
SET @commandlog_missing_cols += N'CommandType, ';
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.CommandLog') AND name = N'DatabaseName')
SET @commandlog_missing_cols += N'DatabaseName, ';
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.CommandLog') AND name = N'SchemaName')
SET @commandlog_missing_cols += N'SchemaName, ';
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.CommandLog') AND name = N'ObjectName')
SET @commandlog_missing_cols += N'ObjectName, ';
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.CommandLog') AND name = N'StatisticsName')
SET @commandlog_missing_cols += N'StatisticsName, ';
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.CommandLog') AND name = N'ExtendedInfo')
SET @commandlog_missing_cols += N'ExtendedInfo, ';
IF LEN(@commandlog_missing_cols) > 0
BEGIN
SET @commandlog_missing_cols = LEFT(@commandlog_missing_cols, LEN(@commandlog_missing_cols) - 2); /* trim trailing ", " */
DECLARE @commandlog_warn nvarchar(1000) =
N'WARNING: dbo.CommandLog schema may be incompatible. Expected columns missing: '
+ @commandlog_missing_cols + N'. Logging may fail.';
RAISERROR(@commandlog_warn, 10, 1) WITH NOWAIT;
END;
/*
v2.5: CommandLog index advisory (#31).
Large CommandLog tables (5M+ rows, common on busy instances running multiple maintenance
jobs) cause full scans on @i_cleanup_orphaned_runs, @LongRunningThresholdMinutes, and progress
queries. A nonclustered index leading on CommandType eliminates these scans.
*/
IF NOT EXISTS
(
SELECT 1
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.object_id = OBJECT_ID(N'dbo.CommandLog')
AND i.type IN (1, 2) /* clustered or nonclustered */
AND c.name = N'CommandType'
AND ic.key_ordinal = 1
)
BEGIN
/* #150: Build advisory DDL dynamically based on columns that actually exist in this schema */
DECLARE
@cmdlog_object_id int = OBJECT_ID(N'dbo.CommandLog'),
@advisory_include nvarchar(500) = N'';
SELECT @advisory_include = @advisory_include +
CASE WHEN @advisory_include = N'' THEN N'' ELSE N', ' END + c.name
FROM (VALUES
(N'DatabaseName'), (N'SchemaName'), (N'ObjectName'),
(N'StatisticsName'), (N'EndTime'), (N'ErrorNumber')
) AS cols(name)
JOIN sys.columns AS c
ON c.object_id = @cmdlog_object_id
AND c.name = cols.name COLLATE DATABASE_DEFAULT;
RAISERROR(N'ADVISORY: dbo.CommandLog has no index leading on CommandType. On large tables this causes full scans during orphan cleanup and adaptive sampling. Consider:', 10, 1) WITH NOWAIT;
IF @advisory_include <> N''
RAISERROR(N' CREATE NONCLUSTERED INDEX IX_CommandLog_CommandType_StartTime ON dbo.CommandLog (CommandType, StartTime) INCLUDE (%s);', 10, 1, @advisory_include) WITH NOWAIT;
ELSE
RAISERROR(N' CREATE NONCLUSTERED INDEX IX_CommandLog_CommandType_StartTime ON dbo.CommandLog (CommandType, StartTime);', 10, 1) WITH NOWAIT;
END;