-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_IndexCleanup.sql
More file actions
7182 lines (6870 loc) · 237 KB
/
sp_IndexCleanup.sql
File metadata and controls
7182 lines (6870 loc) · 237 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_WARNINGS ON;
SET ARITHABORT ON;
SET CONCAT_NULL_YIELDS_NULL ON;
SET QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
SET IMPLICIT_TRANSACTIONS OFF;
SET STATISTICS TIME, IO OFF;
GO
/*
██╗███╗ ██╗██████╗ ███████╗██╗ ██╗
██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝
██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝
██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗
██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗
╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝
██████╗██╗ ███████╗ █████╗ ███╗ ██╗██╗ ██╗██████╗
██╔════╝██║ ██╔════╝██╔══██╗████╗ ██║██║ ██║██╔══██╗
██║ ██║ █████╗ ███████║██╔██╗ ██║██║ ██║██████╔╝
██║ ██║ ██╔══╝ ██╔══██║██║╚██╗██║██║ ██║██╔═══╝
╚██████╗███████╗███████╗██║ ██║██║ ╚████║╚██████╔╝██║
╚═════╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
For usage and licensing details, run:
EXECUTE sp_IndexCleanup
@help = 1;
For working through errors:
EXECUTE sp_IndexCleanup
@debug = 1;
For support, head over to GitHub:
https://code.erikdarling.com
*/
IF OBJECT_ID('dbo.sp_IndexCleanup', 'P') IS NULL
BEGIN
EXECUTE ('CREATE PROCEDURE dbo.sp_IndexCleanup AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_IndexCleanup
(
@database_name sysname = NULL, /*focus on a single database*/
@schema_name sysname = NULL, /*use when focusing on a single table/view, or to a single schema with no table name*/
@table_name sysname = NULL, /*use when focusing on a single table or view*/
@min_reads bigint = 0, /*only look at indexes with a minimum number of reads*/
@min_writes bigint = 0, /*only look at indexes with a minimum number of writes*/
@min_size_gb decimal(10,2) = 0, /*only look at indexes with a minimum size*/
@min_rows bigint = 0, /*only look at indexes with a minimum number of rows*/
@dedupe_only bit = 'false', /*only perform deduplication, don't mark unused indexes for removal*/
@get_all_databases bit = 'false', /*looks for all accessible user databases and returns combined results*/
@include_databases nvarchar(MAX) = NULL, /*comma-separated list of databases to include (only when @get_all_databases = 1)*/
@exclude_databases nvarchar(MAX) = NULL, /*comma-separated list of databases to exclude (only when @get_all_databases = 1)*/
@help bit = 'false', /*learn about the procedure and parameters*/
@debug bit = 'false', /*print dynamic sql, show temp table contents*/
@version varchar(20) = NULL OUTPUT, /*script version number*/
@version_date datetime = NULL OUTPUT /*script version date*/
)
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
SELECT
@version = '2.5',
@version_date = '20260420';
IF
/* Check SQL Server 2012+ for FORMAT and CONCAT functions */
(
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) NOT IN (5, 8) /* Not Azure SQL DB or Managed Instance */
AND CONVERT
(
integer,
SUBSTRING
(
CONVERT
(
varchar(20),
SERVERPROPERTY('ProductVersion')
),
1,
2
)
) < 11) /* Pre-2012 */
BEGIN
RAISERROR('This procedure requires SQL Server 2012 (11.0) or later due to the use of FORMAT and CONCAT functions.', 11, 1);
RETURN;
END;
/*
Help section, for help.
Will become more helpful when out of beta.
*/
IF @help = 1
BEGIN
SELECT
help = N'hello, i am sp_IndexCleanup'
UNION ALL
SELECT
help = N'this is a script to help clean up unused and duplicate indexes.'
UNION ALL
SELECT
help = N'it will also help you add page compression to uncompressed indexes.'
UNION ALL
SELECT
help = N'always validate all changes against a non-production environment!'
UNION ALL
SELECT
help = N'please test carefully.'
UNION ALL
SELECT
help = N'brought to you by erikdarling.com / code.erikdarling.com';
/*
Parameters
*/
SELECT
parameter_name =
ap.name,
data_type =
t.name,
description =
CASE
ap.name
WHEN N'@database_name' THEN 'the name of the database you wish to analyze'
WHEN N'@schema_name' THEN 'limits analysis to tables in the specified schema when used without @table_name'
WHEN N'@table_name' THEN 'the table or view name to filter indexes by, requires @schema_name if not dbo'
WHEN N'@min_reads' THEN 'minimum number of reads for an index to be considered used'
WHEN N'@min_writes' THEN 'minimum number of writes for an index to be considered used'
WHEN N'@min_size_gb' THEN 'minimum size in GB for an index to be analyzed'
WHEN N'@min_rows' THEN 'minimum number of rows for a table to be analyzed'
WHEN N'@dedupe_only' THEN 'only perform index deduplication, do not mark unused indexes for removal'
WHEN N'@get_all_databases' THEN 'set to 1 to analyze all accessible user databases'
WHEN N'@include_databases' THEN 'comma-separated list of databases to include when @get_all_databases = 1'
WHEN N'@exclude_databases' THEN 'comma-separated list of databases to exclude when @get_all_databases = 1'
WHEN N'@help' THEN 'displays this help information'
WHEN N'@debug' THEN 'prints debug information during execution'
WHEN N'@version' THEN 'returns the version number of the procedure'
WHEN N'@version_date' THEN 'returns the date this version was released'
ELSE NULL
END,
valid_inputs =
CASE
ap.name
WHEN N'@database_name' THEN 'the name of a database you care about indexes in'
WHEN N'@schema_name' THEN 'schema name or NULL for all schemas'
WHEN N'@table_name' THEN 'table (or view) name or NULL for all tables'
WHEN N'@min_reads' THEN 'any positive integer or 0'
WHEN N'@min_writes' THEN 'any positive integer or 0'
WHEN N'@min_size_gb' THEN 'any positive decimal or 0'
WHEN N'@min_rows' THEN 'any positive integer or 0'
WHEN N'@dedupe_only' THEN '0 or 1 - only perform index deduplication, do not mark unused indexes for removal'
WHEN N'@get_all_databases' THEN '0 or 1'
WHEN N'@include_databases' THEN 'comma-separated list of database names'
WHEN N'@exclude_databases' THEN 'comma-separated list of database names'
WHEN N'@help' THEN '0 or 1'
WHEN N'@debug' THEN '0 or 1'
WHEN N'@version' THEN 'OUTPUT parameter'
WHEN N'@version_date' THEN 'OUTPUT parameter'
ELSE NULL
END,
defaults =
CASE
ap.name
WHEN N'@database_name' THEN 'NULL'
WHEN N'@schema_name' THEN 'NULL'
WHEN N'@table_name' THEN 'NULL'
WHEN N'@min_reads' THEN '0'
WHEN N'@min_writes' THEN '0'
WHEN N'@min_size_gb' THEN '0'
WHEN N'@min_rows' THEN '0'
WHEN N'@dedupe_only' THEN 'false'
WHEN N'@get_all_databases' THEN 'false'
WHEN N'@include_databases' THEN 'NULL'
WHEN N'@exclude_databases' THEN 'NULL'
WHEN N'@help' THEN 'false'
WHEN N'@debug' THEN 'false'
WHEN N'@version' THEN 'NULL'
WHEN N'@version_date' THEN 'NULL'
ELSE NULL
END
FROM sys.all_parameters AS ap
JOIN sys.all_objects AS o
ON ap.object_id = o.object_id
JOIN sys.types AS t
ON ap.system_type_id = t.system_type_id
AND ap.user_type_id = t.user_type_id
WHERE o.name = N'sp_IndexCleanup'
ORDER BY
ap.parameter_id
OPTION(MAXDOP 1, RECOMPILE);
SELECT
mit_license_yo = 'i am MIT licensed, so like, do whatever'
UNION ALL
SELECT
mit_license_yo = 'see printed messages for full license';
RAISERROR('
MIT License
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
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.
', 0, 1) WITH NOWAIT;
RETURN;
END;
IF @debug = 1
BEGIN
RAISERROR('Declaring variables', 0, 0) WITH NOWAIT;
END;
DECLARE
/*general script variables*/
@sql nvarchar(MAX) = N'',
@object_id integer = NULL,
@full_object_name nvarchar(768) = NULL,
@uptime_warning bit = 0, /* Will set after @uptime_days is calculated */
/*print variables*/
@online bit =
CASE
WHEN
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) IN (3, 5, 8)
THEN 'true' /* Enterprise, Azure SQL DB, Managed Instance */
ELSE 'false'
END,
/* Compression variables */
@can_compress bit =
CASE
WHEN
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) IN (3, 5, 8)
OR
(
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) = 2
AND CONVERT
(
integer,
SUBSTRING
(
CONVERT
(
varchar(20),
SERVERPROPERTY('ProductVersion')
),
1,
2
)
) >= 13
)
THEN 1
ELSE 0
END,
/* OPTIMIZE_FOR_SEQUENTIAL_KEY variables (SQL 2019+, Azure SQL DB, and Managed Instance) */
@supports_optimize_for_sequential_key bit =
CASE
/* Azure SQL DB or Managed Instance */
WHEN CONVERT(integer, SERVERPROPERTY('EngineEdition')) IN (5, 8)
THEN 1
/* SQL Server 2019+ (Enterprise or Standard) */
WHEN CONVERT(integer, SERVERPROPERTY('EngineEdition')) IN (2, 3)
AND CONVERT
(
integer,
SUBSTRING
(
CONVERT
(
varchar(20),
SERVERPROPERTY('ProductVersion')
),
1,
2
)
) >= 15
THEN 1
ELSE 0
END,
/* Temporal tables support (SQL 2016+, Azure SQL DB, and Managed Instance) */
@supports_temporal_tables bit =
CASE
/* Azure SQL DB or Managed Instance */
WHEN CONVERT(integer, SERVERPROPERTY('EngineEdition')) IN (5, 8)
THEN 1
/* SQL Server 2016+ */
WHEN CONVERT
(
integer,
SUBSTRING
(
CONVERT
(
varchar(20),
SERVERPROPERTY('ProductVersion')
),
1,
2
)
) >= 13
THEN 1
ELSE 0
END,
@is_azure_sql_db bit =
CASE
WHEN CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) = 5
THEN 1
ELSE 0
END,
@uptime_days nvarchar(10) =
(
SELECT
DATEDIFF
(
DAY,
osi.sqlserver_start_time,
SYSDATETIME()
)
FROM sys.dm_os_sys_info AS osi
),
@database_cursor CURSOR,
@current_database_name sysname,
@current_database_id integer,
@error_msg nvarchar(2048),
@conflict_list nvarchar(MAX) = N'',
@rc bigint;
/* Set uptime warning flag after @uptime_days is calculated */
SELECT
@uptime_warning =
CASE
WHEN CONVERT(integer, @uptime_days) < 14
THEN 1
ELSE 0
END;
/* Auto-enable dedupe_only mode if server uptime is low */
IF CONVERT(integer, @uptime_days) <= 7 AND @dedupe_only = 0
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Server uptime is less than 7 days. Automatically enabling @dedupe_only mode.', 0, 1) WITH NOWAIT;
END;
SET @dedupe_only = 1;
END;
/*
Initial checks for object validity
*/
IF @debug = 1
BEGIN
RAISERROR('Checking parameters...', 0, 0) WITH NOWAIT;
END;
IF @schema_name IS NULL
AND @table_name IS NOT NULL
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Parameter @schema_name cannot be NULL when specifying a table, defaulting to dbo', 10, 1) WITH NOWAIT;
END;
SET @schema_name = N'dbo';
END;
IF @min_reads < 0
OR @min_reads IS NULL
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Parameter @min_reads cannot be NULL or negative. Setting to 0.', 10, 1) WITH NOWAIT;
END;
SET @min_reads = 0;
END;
IF @min_writes < 0
OR @min_writes IS NULL
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Parameter @min_writes cannot be NULL or negative. Setting to 0.', 10, 1) WITH NOWAIT;
END;
SET @min_writes = 0;
END;
IF @min_size_gb < 0
OR @min_size_gb IS NULL
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Parameter @min_size_gb cannot be NULL or negative. Setting to 0.', 10, 1) WITH NOWAIT;
END;
SET @min_size_gb = 0;
END;
IF @min_rows < 0
OR @min_rows IS NULL
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Parameter @min_rows cannot be NULL or negative. Setting to 0.', 10, 1) WITH NOWAIT;
END;
SET @min_rows = 0;
END;
/*
Temp tables!
*/
IF @debug = 1
BEGIN
RAISERROR('Creating temp tables', 0, 0) WITH NOWAIT;
END;
CREATE TABLE
#filtered_objects
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,
table_name sysname NOT NULL,
index_id integer NOT NULL,
index_name sysname NOT NULL,
can_compress bit NOT NULL
);
CREATE CLUSTERED INDEX
filtered_objects
ON #filtered_objects
(database_id, schema_id, object_id, index_id);
CREATE TABLE
#operational_stats
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,
table_name sysname NOT NULL,
index_id integer NOT NULL,
index_name sysname NOT NULL,
range_scan_count bigint NULL,
singleton_lookup_count bigint NULL,
forwarded_fetch_count bigint NULL,
lob_fetch_in_pages bigint NULL,
row_overflow_fetch_in_pages bigint NULL,
leaf_insert_count bigint NULL,
leaf_update_count bigint NULL,
leaf_delete_count bigint NULL,
leaf_ghost_count bigint NULL,
nonleaf_insert_count bigint NULL,
nonleaf_update_count bigint NULL,
nonleaf_delete_count bigint NULL,
leaf_allocation_count bigint NULL,
nonleaf_allocation_count bigint NULL,
row_lock_count bigint NULL,
row_lock_wait_count bigint NULL,
row_lock_wait_in_ms bigint NULL,
page_lock_count bigint NULL,
page_lock_wait_count bigint NULL,
page_lock_wait_in_ms bigint NULL,
index_lock_promotion_attempt_count bigint NULL,
index_lock_promotion_count bigint NULL,
page_latch_wait_count bigint NULL,
page_latch_wait_in_ms bigint NULL,
tree_page_latch_wait_count bigint NULL,
tree_page_latch_wait_in_ms bigint NULL,
page_io_latch_wait_count bigint NULL,
page_io_latch_wait_in_ms bigint NULL,
page_compression_attempt_count bigint NULL,
page_compression_success_count bigint NULL,
/* Hash column for optimized matching */
index_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id) +
CONVERT(varbinary(8), index_id)
)
) PERSISTED
PRIMARY KEY CLUSTERED
(database_id, schema_id, object_id, index_id)
);
CREATE TABLE
#partition_stats
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,
table_name sysname NOT NULL,
index_id integer NOT NULL,
index_name sysname NULL,
partition_id bigint NOT NULL,
partition_number integer NOT NULL,
total_rows bigint NULL,
total_space_gb decimal(38, 4) NULL, /* Using 4 decimal places for GB to maintain precision */
reserved_lob_gb decimal(38, 4) NULL, /* Using 4 decimal places for GB to maintain precision */
reserved_row_overflow_gb decimal(38, 4) NULL, /* Using 4 decimal places for GB to maintain precision */
data_compression_desc nvarchar(60) NULL,
built_on sysname NULL,
partition_function_name sysname NULL,
partition_columns nvarchar(max),
/* Hash column for optimized matching */
index_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id) +
CONVERT(varbinary(8), index_id)
)
) PERSISTED
PRIMARY KEY CLUSTERED
(database_id, schema_id, object_id, index_id, partition_id)
);
CREATE TABLE
#index_details
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,
table_name sysname NOT NULL,
index_id integer NOT NULL,
index_name sysname NULL,
column_name sysname NOT NULL,
column_id integer NOT NULL,
is_primary_key bit NULL,
is_unique bit NULL,
is_unique_constraint bit NULL,
is_indexed_view integer NOT NULL,
is_foreign_key bit NULL,
is_foreign_key_reference bit NULL,
key_ordinal tinyint NOT NULL,
index_column_id integer NOT NULL,
is_descending_key bit NOT NULL,
is_included_column bit NULL,
filter_definition nvarchar(max) NULL,
is_max_length integer NOT NULL,
optimize_for_sequential_key bit NOT NULL,
user_seeks bigint NOT NULL,
user_scans bigint NOT NULL,
user_lookups bigint NOT NULL,
user_updates bigint NOT NULL,
last_user_seek datetime NULL,
last_user_scan datetime NULL,
last_user_lookup datetime NULL,
last_user_update datetime NULL,
is_eligible_for_dedupe bit NOT NULL,
/* Hash columns for optimized matching */
index_hash AS
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), CONVERT(integer, database_id)) +
CONVERT(varbinary(8), CONVERT(integer, object_id)) +
CONVERT(varbinary(8), CONVERT(integer, index_id))
) PERSISTED,
column_position_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id) +
CONVERT(varbinary(max), column_name) +
CONVERT(varbinary(8), key_ordinal)
)
) PERSISTED,
scope_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id)
)
) PERSISTED
PRIMARY KEY CLUSTERED
(database_id, schema_id, object_id, index_id, column_id)
);
CREATE TABLE
#index_analysis
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,
table_name sysname NOT NULL,
index_id integer NOT NULL,
index_name sysname NOT NULL,
is_unique bit NULL,
key_columns nvarchar(MAX) NULL,
included_columns nvarchar(MAX) NULL,
filter_definition nvarchar(MAX) NULL,
/* Query plan for original CREATE INDEX statement */
original_index_definition nvarchar(MAX) NULL,
/*
Consolidation rule that matched (e.g., Key Duplicate, Key Subset, etc)
For exact duplicates, use one of: Exact Duplicate, Reverse Duplicate, or Equal Except For Filter
*/
consolidation_rule nvarchar(256) NULL,
/*
Action to take (e.g., DISABLE, MERGE INCLUDES, KEEP)
If NULL, no action to be taken
*/
action nvarchar(100) NULL,
/* Target index to merge with or use instead of this one */
target_index_name sysname NULL,
/* When this is a target, the index which points to it as a supersedes in consolidation */
superseded_by nvarchar(4000) NULL,
/* Priority score from 0-1 to determine which index to keep (higher is better) */
index_priority decimal(10,6) NULL,
/* Hash columns for optimized matching */
scope_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id)
)
) PERSISTED,
exact_match_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
ISNULL(key_columns, N'') + N'|' +
ISNULL(included_columns, N'') + N'|' +
ISNULL(filter_definition, N'')
)
) PERSISTED,
key_filter_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
ISNULL(key_columns, N'') + N'|' +
ISNULL(filter_definition, N'')
)
) PERSISTED,
index_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id) +
CONVERT(varbinary(8), index_id)
)
) PERSISTED
);
CREATE CLUSTERED INDEX
index_analysis
ON #index_analysis
(database_id, schema_id, object_id, index_id);
/*
Nonclustered indexes on hash columns for optimized matching.
These support faster joins in consolidation rules by reducing
multi-column comparisons to single hash comparisons.
*/
CREATE INDEX
scope_hash
ON #index_analysis
(scope_hash)
INCLUDE
(index_name);
CREATE INDEX
exact_match_hash
ON #index_analysis
(exact_match_hash);
CREATE INDEX
key_filter_hash
ON #index_analysis
(key_filter_hash);
/*
Nonclustered indexes on #index_details hash columns.
These support faster correlation in EXISTS clauses by reducing
multi-column comparisons to single hash comparisons.
*/
CREATE INDEX
index_hash
ON #index_details
(index_hash);
CREATE INDEX
column_position_hash
ON #index_details
(column_position_hash);
CREATE INDEX
scope_hash
ON #index_details
(scope_hash);
CREATE TABLE
#compression_eligibility
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,
table_name sysname NOT NULL,
index_id integer NOT NULL,
index_name sysname NOT NULL,
can_compress bit NOT NULL,
reason nvarchar(200) NULL,
/* Hash column for optimized matching */
index_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id) +
CONVERT(varbinary(8), index_id)
)
) PERSISTED
PRIMARY KEY CLUSTERED
(database_id, schema_id, object_id, index_id, can_compress)
);
CREATE TABLE
#index_cleanup_results
(
result_type varchar(100) NOT NULL,
sort_order integer NOT NULL,
database_name nvarchar(max) NULL,
schema_name nvarchar(max) NULL,
table_name sysname NULL,
index_name sysname NULL,
script_type nvarchar(60) NULL, /* Type of script (e.g., MERGE SCRIPT, DISABLE SCRIPT, etc.) */
consolidation_rule nvarchar(256) NULL, /* Reason for action (e.g., Exact Duplicate, Key Subset) */
target_index_name sysname NULL, /* If this index is a duplicate, indicates which index is the preferred one */
superseded_info nvarchar(4000) NULL, /* If this is a kept index, indicates which indexes it supersedes */
additional_info nvarchar(max) NULL, /* Additional information about the action */
original_index_definition nvarchar(max) NULL, /* Original statement to create the index */
index_size_gb decimal(38, 4) NULL, /* Size of the index in GB */
index_rows bigint NULL, /* Number of rows in the index */
index_reads bigint NULL, /* Total reads (seeks + scans + lookups) */
index_writes bigint NULL, /* Total writes */
script nvarchar(max) NULL /* Script to execute the action */
);
CREATE TABLE
#key_duplicate_dedupe
(
database_id integer NOT NULL,
object_id integer NOT NULL,
database_name sysname NOT NULL,
schema_name sysname NOT NULL,
table_name sysname NOT NULL,
base_key_columns nvarchar(max) NULL,
filter_definition nvarchar(max) NULL,
winning_index_name sysname NULL,
index_list nvarchar(max) NULL,
/* Hash columns for optimized matching */
scope_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id)
)
) PERSISTED,
key_filter_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
ISNULL(base_key_columns, N'') + N'|' +
ISNULL(filter_definition, N'')
)
) PERSISTED
);
CREATE TABLE
#include_subset_dedupe
(
database_id integer NOT NULL,
object_id integer NOT NULL,
subset_index_name sysname NULL,
superset_index_name sysname NULL,
subset_included_columns nvarchar(max) NULL,
superset_included_columns nvarchar(max) NULL,
/* Hash column for optimized matching */
scope_hash AS
CONVERT
(
varbinary(32),
HASHBYTES
(
'SHA2_256',
CONVERT(varbinary(8), database_id) +
CONVERT(varbinary(8), object_id)
)
) PERSISTED
);
/* Create a new temp table for detailed reporting statistics */
CREATE TABLE
#index_reporting_stats
(
summary_level varchar(20) NOT NULL, /* 'DATABASE', 'TABLE', 'INDEX', 'SUMMARY' */
database_name sysname NULL,
schema_name sysname NULL,
table_name sysname NULL,
index_name sysname NULL,
server_uptime_days integer NULL,
uptime_warning bit NULL,
tables_analyzed integer NULL,
index_count integer NULL,
total_size_gb decimal(38, 4) NULL,
total_rows bigint NULL,
unused_indexes integer NULL,
unused_size_gb decimal(38, 4) NULL,
indexes_to_disable integer NULL,
indexes_to_merge integer NULL,
compressable_indexes integer NULL,
avg_indexes_per_table decimal(10, 2) NULL,
space_saved_gb decimal(10, 4) NULL,
compression_min_savings_gb decimal(10, 4) NULL,
compression_max_savings_gb decimal(10, 4) NULL,
total_min_savings_gb decimal(10, 4) NULL,
total_max_savings_gb decimal(10, 4) NULL,
/* Index usage metrics */
total_reads bigint NULL,
total_writes bigint NULL,
user_seeks bigint NULL,
user_scans bigint NULL,
user_lookups bigint NULL,
user_updates bigint NULL,
/* Operational stats */
range_scan_count bigint NULL,
singleton_lookup_count bigint NULL,
/* Lock stats */
row_lock_count bigint NULL,
row_lock_wait_count bigint NULL,
row_lock_wait_in_ms bigint NULL,
page_lock_count bigint NULL,
page_lock_wait_count bigint NULL,
page_lock_wait_in_ms bigint NULL,
/* Latch stats */
page_latch_wait_count bigint NULL,
page_latch_wait_in_ms bigint NULL,
page_io_latch_wait_count bigint NULL,
page_io_latch_wait_in_ms bigint NULL,
/* Misc stats */
forwarded_fetch_count bigint NULL,
leaf_insert_count bigint NULL,
leaf_update_count bigint NULL,
leaf_delete_count bigint NULL
);
/* Create temp tables for database filtering */
CREATE TABLE
#include_databases
(
database_name sysname NOT NULL PRIMARY KEY CLUSTERED
);
CREATE TABLE
#exclude_databases
(
database_name sysname NOT NULL PRIMARY KEY CLUSTERED
);
CREATE TABLE
#databases
(
database_name sysname NOT NULL PRIMARY KEY CLUSTERED,
database_id integer NOT NULL
);
CREATE TABLE
#requested_but_skipped_databases
(
database_name sysname NOT NULL PRIMARY KEY CLUSTERED,
reason nvarchar(100) NOT NULL
);
CREATE TABLE
#computed_columns_analysis
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,
table_name sysname NOT NULL,
column_id integer NOT NULL,
column_name sysname NOT NULL,
definition nvarchar(max) NULL,
contains_udf bit NOT NULL,
udf_names nvarchar(max) NULL,
PRIMARY KEY CLUSTERED
(database_id, schema_id, object_id, column_id)
);
CREATE TABLE
#check_constraints_analysis
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
schema_id integer NOT NULL,
schema_name sysname NOT NULL,
object_id integer NOT NULL,