-
Notifications
You must be signed in to change notification settings - Fork 681
/
dbo.sp_BlitzInMemoryOLTP.sql
2046 lines (1757 loc) · 76.2 KB
/
dbo.sp_BlitzInMemoryOLTP.sql
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
DECLARE @msg NVARCHAR(MAX) = N'';
-- Must be a compatible, on-prem version of SQL (2014+)
IF ( (SELECT SERVERPROPERTY ('EDITION')) <> 'SQL Azure'
AND (SELECT PARSENAME(CONVERT(NVARCHAR(128), SERVERPROPERTY ('PRODUCTVERSION')), 4)) < 12
)
-- or Azure Database (not Azure Data Warehouse), running at database compat level 120+
OR ( (SELECT SERVERPROPERTY ('EDITION')) = 'SQL Azure'
AND (SELECT SERVERPROPERTY ('ENGINEEDITION')) = 5
AND (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) < 120
)
BEGIN
SELECT @msg = N'Sorry, sp_BlitzInMemoryOLTP doesn''t work on versions of SQL prior to 2014.' + REPLICATE(CHAR(13), 7933);
PRINT @msg;
RETURN;
END;
IF OBJECT_ID('dbo.sp_BlitzInMemoryOLTP', 'P') IS NULL
EXECUTE ('CREATE PROCEDURE dbo.sp_BlitzInMemoryOLTP AS SELECT 1;');
GO
ALTER PROCEDURE dbo.sp_BlitzInMemoryOLTP(
@instanceLevelOnly BIT = 0
, @dbName NVARCHAR(4000) = N'ALL'
, @tableName NVARCHAR(4000) = NULL
, @debug BIT = 0
, @VersionDate DATETIME = NULL OUTPUT
)
/*
.SYNOPSIS
Get detailed information about In-Memory SQL Server objects
.DESCRIPTION
Get detailed information about In-Memory SQL Server objects
Tested on SQL Server: 2014, 2016, 2017
tested on Azure SQL Database
NOT tested on Azure Managed Instances
.PARAMETER @instanceLevelOnly
Only check instance In-Memory related information
.PARAMETER @dbName
Check database In-Memory objects for specified database
.PARAMETER @tableName
Check database In-Memory objects for specified tablename
.PARAMETER @debug
Only PRINT dynamic sql statements without executing it
.EXAMPLE
EXEC sp_BlitzInMemoryOLTP;
-- Get all In-memory information
.EXAMPLE
EXEC sp_BlitzInMemoryOLTP @dbName = N'ಠ ಠ';
-- Get In-memory information for database with name ಠ ಠ
.EXAMPLE
EXEC sp_BlitzInMemoryOLTP @instanceLevelOnly = 1;
-- Get only instance In-Memory information
.EXAMPLE
EXEC sp_BlitzInMemoryOLTP @debug = 1;
-- PRINT dynamic sql statements without executing it
.LICENSE MIT
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.
.NOTE
Author: Ned Otter
Version: 2.0
Original link: http://nedotter.com/archive/2017/10/in-memory-oltp-diagnostic-script/
Release Link: https://github.com/ktaranov/sqlserver-kit/blob/master/Stored_Procedure/sp_BlitzInMemoryOLTP.sql
Main Contributors: Ned Otter, Konstantin Taranov, Aleksey Nagorskiy
*/
AS
DECLARE @ScriptVersion VARCHAR(30);
SET @ScriptVersion = '1.8';
SET @VersionDate = '20180801';
BEGIN TRY
SET NOCOUNT ON;
DECLARE @RunningOnAzureSQLDB BIT = 0;
DECLARE @crlf VARCHAR(10) = CHAR(10);
DECLARE @Edition NVARCHAR(MAX) = CAST(SERVERPROPERTY('Edition') AS NVARCHAR(128))
, @errorMessage NVARCHAR(512);
DECLARE @Version INT = CONVERT(INT, SERVERPROPERTY('ProductMajorVersion'));
IF @debug = 1 PRINT('--@Version = ' + CAST(@Version AS VARCHAR(30)));
/*
###################################################
if we get here, we are running at least SQL 2014, but that version
only runs In-Memory if we are using Enterprise Edition
NOTE: Azure SQL database changes this equation
###################################################
*/
/*
SERVERPROPERTY('EngineEdition')
1 = Personal or Desktop Engine (Not available in SQL Server 2005 and later versions.)
,2 = Standard (This is returned for Standard, Web, and Business Intelligence.)
,3 = Enterprise (This is returned for Evaluation, Developer, and both Enterprise editions.)
,4 = Express (This is returned for Express, Express with Tools and Express with Advanced Services)
,5 = SQL Database
,6 = SQL Data Warehouse
,8 = Managed Instance
*/
SELECT @RunningOnAzureSQLDB =
CASE
WHEN SERVERPROPERTY('EngineEdition') IN (5, 6, 8) THEN 1
ELSE 0
END;
-- Database level: we are running SQL Database or SQL Data Warehouse, but this specific database does not support XTP
IF (@RunningOnAzureSQLDB = 1 AND DatabasePropertyEx(DB_NAME(), 'IsXTPSupported') = 0)
BEGIN
SET @errorMessage = 'For Azure SQL Database, In-Memory OLTP is only suppported on the Premium tier';
THROW 55001, @errorMessage, 1;
END;
-- not on Azure, so we need to check versions/Editions
-- SQL 2014 only supports XTP on Enterprise edition
IF (SERVERPROPERTY('EngineEdition') IN (2, 4)) AND @Version = 12 AND (@Edition NOT LIKE 'Enterprise%' AND @Edition NOT LIKE 'Developer%')
BEGIN
SET @errorMessage = CONCAT('For SQL 2014, In-Memory OLTP is only suppported on Enterprise Edition. You are running SQL Server edition: ', @Edition);
THROW 55002, @errorMessage, 1;
END;
-- We're not running on Azure, so we need to check versions/Editions
-- SQL 2016 non-Enterprise only supports XTP after SP1
DECLARE @BuildString VARCHAR(4) = CONVERT(VARCHAR(4), SERVERPROPERTY('ProductBuild'));
IF (SERVERPROPERTY('EngineEdition') IN (2, 4)) AND @Version = 13 AND (@BuildString < 4001)
-- 13.0.4001.0 is the minimum build for XTP support
BEGIN
SET @errorMessage = 'For SQL 2016, In-Memory OLTP is only suppported on non-Enterprise Edition as of SP1';
THROW 55003, @errorMessage, 1;
END;
/*
######################################################################################################################
DATABASE LEVEL
######################################################################################################################
*/
DECLARE @resultsDatabaseLayout TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,fileGroupName NVARCHAR(MAX)
,fileName NVARCHAR(MAX)
,[containerName/fileType] NVARCHAR(MAX)
,Name NVARCHAR(MAX)
,IsContainer NVARCHAR(MAX)
,fileGroupDescription NVARCHAR(MAX)
,fileGroupState NVARCHAR(MAX)
,sizeKB NVARCHAR(MAX)
,sizeMB NVARCHAR(MAX)
,sizeGB NVARCHAR(MAX)
,totalSizeMB NVARCHAR(MAX)
);
DECLARE @resultsNativeModuleCount TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,[Number of modules] INT
);
DECLARE @resultsInMemTables TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,tableName NVARCHAR(MAX)
,[rowCount] INT
,durability_desc NVARCHAR(MAX)
,temporal_type_desc NVARCHAR(MAX)
,memoryAllocatedForTableKB NVARCHAR(MAX)
,memoryUsedByTableKB NVARCHAR(MAX)
,memoryAllocatedForIndexesKB NVARCHAR(MAX)
,memoryUsedByIndexesKB NVARCHAR(MAX)
);
DECLARE @resultsIndexes TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,tableName NVARCHAR(MAX)
,indexName NVARCHAR(MAX)
,memory_consumer_id INT
,consumerType NVARCHAR(MAX)
,description NVARCHAR(MAX)
,allocations INT
,allocatedBytesMB NVARCHAR(MAX)
,usedBytesMB NVARCHAR(MAX)
);
DECLARE @resultsHashBuckets TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,[Schema] NVARCHAR(MAX)
,TableName NVARCHAR(MAX)
,indexName NVARCHAR(MAX)
,totalBucketCount BIGINT
,emptyBucketCount BIGINT
,emptyBucketPercent INT
,avg_ChainLength INT
,max_ChainLength BIGINT
,[Free buckets status] NVARCHAR(MAX)
,[avg_chain_length status] BIGINT
);
DECLARE @resultsIndexCount TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,tableName NVARCHAR(MAX)
,indexCount INT
);
DECLARE @resultsNativeModules TABLE
(
[object] NVARCHAR(MAX)
,Name NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,[type] NVARCHAR(MAX)
,[definition] NVARCHAR(MAX)
);
DECLARE @resultsNativeLoaded TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,moduleName NVARCHAR(MAX)
,object_id INT
);
DECLARE @resultsTemporal TABLE
(
[object] NVARCHAR(256)
,databaseName NVARCHAR(MAX)
,temporalTableSchema NVARCHAR(MAX)
,temporalTableName NVARCHAR(MAX)
,internalHistoryTableName NVARCHAR(MAX)
,allocatedBytesForInternalHistoryTable BIGINT
,usedBytesForInternalHistoryTable BIGINT
);
DECLARE @resultsMemoryConsumerForLOBs TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,tableName NVARCHAR(MAX)
,columnName NVARCHAR(MAX)
,typeDescription NVARCHAR(MAX)
,memoryConsumerTypeDescription NVARCHAR(MAX)
,memoryConsumerDescription NVARCHAR(MAX)
,allocatedBytes INT
,usedBytes INT
);
DECLARE @resultsTableTypes TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,[Schema] NVARCHAR(MAX)
,[Name] NVARCHAR(MAX)
);
DECLARE @resultsNativeModuleStats TABLE
(
[object] NVARCHAR(MAX)
,databaseName NVARCHAR(MAX)
,object_id INT
,object_name NVARCHAR(MAX)
,cached_time DATETIME
,last_execution_time DATETIME
,execution_count INT
,total_worker_time INT
,last_worker_time INT
,min_worker_time INT
,max_worker_time INT
,total_elapsed_time INT
,last_elapsed_time INT
,min_elapsed_time INT
,max_elapsed_time INT
);
DECLARE @resultsxtp_storage_percent TABLE
(
databaseName NVARCHAR(MAX)
,end_time DATETIME
,xtp_storage_percent DECIMAL(5, 2)
);
CREATE TABLE #resultsContainerDetails
(
[object] NVARCHAR(256)
,databaseName NVARCHAR(256)
,containerName NVARCHAR(256)
,container_id BIGINT
,sizeMB NVARCHAR(256)
,fileCount INT
);
CREATE TABLE #resultsContainerFileDetails
(
[object] NVARCHAR(256)
,databaseName NVARCHAR(256)
,containerName NVARCHAR(256)
,container_id BIGINT
,fileType NVARCHAR(256)
,fileState NVARCHAR(256)
,sizeBytes NVARCHAR(256)
,sizeGB NVARCHAR(256)
,fileCount INT
,fileGroupState NVARCHAR(256)
);
CREATE TABLE #resultsContainerFileSummary
(
[object] NVARCHAR(256)
,databaseName NVARCHAR(256)
,fileType NVARCHAR(256)
,fileState NVARCHAR(256)
,sizeBytes NVARCHAR(256)
,sizeMB NVARCHAR(256)
,fileCount INT
,fileGroupState NVARCHAR(256)
);
IF OBJECT_ID('tempdb..#inmemDatabases') IS NOT NULL DROP TABLE #inmemDatabases;
/*
-- IF we are searching for a specific @tablename, it could exist in >1 database.
-- This is the point at which we should filter, but it might require dynamic SQL,
-- or deleting database names that don't have an object where the name matches.
*/
SELECT QUOTENAME(name) AS name
, database_id
, ROW_NUMBER() OVER (ORDER BY name ASC) AS rowNumber
INTO #inmemDatabases
FROM sys.databases
WHERE name NOT IN ( 'master', 'model', 'tempdb', 'distribution', 'msdb', 'SSISDB')
AND 1 =
CASE
WHEN @RunningOnAzureSQLDB = 1 THEN 1
WHEN @RunningOnAzureSQLDB = 0 AND name = @dbName THEN 1
WHEN @RunningOnAzureSQLDB = 0 AND @dbName = N'ALL' THEN 1
ELSE 0
END
AND state_desc = 'ONLINE';
DECLARE @sql NVARCHAR(MAX) = ''
DECLARE @counter INT = 1
, @MaxRows INT = (SELECT COUNT(*) FROM #inmemDatabases);
WHILE @counter <= @MaxRows
BEGIN
--IF @debug = 1 PRINT('--@counter = ' + CAST(@counter AS VARCHAR(30)) + ';' + @crlf);
IF @tableName IS NOT NULL
SELECT @sql =
CONCAT
(
'DELETE #inmemDatabases '
,'WHERE UPPER(name) = '
,''''
,UPPER(name)
,''''
,' AND NOT EXISTS ('
,'SELECT *
FROM '
,name
,'.sys.objects
WHERE UPPER(name) = '
,''''
,UPPER(@tableName)
,''''
,' AND UPPER(type) = ''U'')'
)
FROM #inmemDatabases
WHERE rowNumber = @counter;
IF @debug = 1 PRINT(@sql);
EXEC (@sql)
SELECT @counter += 1;
END;
ALTER TABLE #inmemDatabases
ADD newRowNumber INT IDENTITY
IF @debug = 1
SELECT 'All ONLINE user databases' AS AllDatabases
,name
,database_id
FROM #inmemDatabases;
IF @dbName IS NULL AND @instanceLevelOnly = 0
BEGIN
SET @errorMessage = '@dbName IS NULL, please specify database name or ALL';
THROW 55004, @errorMessage, 1;
RETURN;
END;
IF (@dbName IS NOT NULL AND @dbName <> N'ALL')
AND (NOT EXISTS (SELECT 1 FROM #inmemDatabases WHERE name = QUOTENAME(@dbName)) AND @instanceLevelOnly = 0)
BEGIN
SET @errorMessage = N'Database [' + @dbName + N'] not found in sys.databases!!!' + @crlf +
N'Did you add N if your database has a unicode name?' + @crlf +
N'Try to exec this: EXEC sp_BlitzInMemoryOLTP @dbName = N''ಠ ಠ_Your_Unicode_DB_Name_ಠ ಠ''';
THROW 55005, @errorMessage, 1;
RETURN;
END;
IF @dbName = 'ALL' AND NOT EXISTS (SELECT 1 FROM #inmemDatabases)
BEGIN
SET @errorMessage = 'ALL was specified, but no memory-optimized databases were found';
THROW 55006, @errorMessage, 1;
RETURN;
END;
-- we can't reference sys.dm_os_loaded_modules if we're on Azure SQL DB
IF @RunningOnAzureSQLDB = 0
BEGIN
IF OBJECT_ID('tempdb..#moduleSplit') IS NOT NULL DROP TABLE #moduleSplit;
CREATE TABLE #moduleSplit
(
rowNumber INT IDENTITY PRIMARY KEY
,value NVARCHAR(MAX) NULL
);
DECLARE @loadedModules TABLE
(
rowNumber INT IDENTITY PRIMARY KEY
,name NVARCHAR(MAX) NULL
);
INSERT @loadedModules
(
name
)
SELECT name
FROM sys.dm_os_loaded_modules AS a
WHERE description = 'XTP Native DLL'
AND PATINDEX('%[_]p[_]%', name) > 0;
DECLARE @maxLoadedModules INT = (SELECT COUNT(*) FROM @loadedModules);
DECLARE @moduleCounter INT = 1;
DECLARE @loadedModuleName NVARCHAR(MAX) = '';
SET @moduleCounter = 1;
WHILE @moduleCounter <= @maxLoadedModules
BEGIN
SELECT @loadedModuleName = name
FROM @loadedModules
WHERE rowNumber = @moduleCounter;
DECLARE @xml XML
, @delimiter NVARCHAR(10);
SET @delimiter = '_';
SET @xml = CAST(('<X>'+REPLACE(@loadedModuleName, @delimiter, '</X><X>')+'</X>') AS XML);
INSERT #moduleSplit
(
value
)
SELECT C.value('.', 'NVARCHAR(1000)') AS value FROM @xml.nodes('X') as X(C);
SELECT @moduleCounter += 1;
END;
END;
IF @instanceLevelOnly = 0
BEGIN
/*
####################################################
Determine which databases are memory-optimized
NOTE: if we are running on Azure SQL DB, we need
to verify in-memory capability without joining to
sys.filegroups
####################################################
*/
SELECT @MaxRows = (SELECT COUNT(*) FROM #inmemDatabases);
SELECT @counter = 1
SELECT @sql = ''
WHILE @counter <= @MaxRows
BEGIN
--IF @debug = 1 PRINT('--@counter = ' + CAST(@counter AS VARCHAR(30)) + ';' + @crlf);
IF @counter = 1
BEGIN
SELECT @sql += ';WITH InMemDatabases AS (';
END;
SELECT @sql +=
CASE
WHEN @counter = 1 THEN '' -- there is exactly 1 database for the entire instance
ELSE @crlf + ' UNION ALL ' + @crlf
END;
SELECT @sql +=
CASE WHEN @RunningOnAzureSQLDB = 0 THEN
CONCAT
(
@crlf
,'SELECT DISTINCT '
, 'N'''
, name
, ''' AS databaseName,' + @crlf
, database_id
, ' AS database_id' + @crlf+ ' FROM '
, name
, '.sys.database_files' + @crlf + ' INNER JOIN '
, name
, '.sys.filegroups ON database_files.data_space_id = filegroups.data_space_id '
, 'WHERE filegroups.type = '
,''''
,'FX'
,''''
)
ELSE
-- if we arrive here and we're running on Azure SQL DB, then the database inherently supports In-Memory OLTP
CONCAT
(
@crlf
,'SELECT '
, 'N'''
, name
, ''' AS databaseName,' + @crlf
, database_id
, ' AS database_id' + @crlf
)
END
FROM #inmemDatabases
WHERE newRowNumber = @counter;
SELECT @counter += 1;
END;
--IF @debug = 1 PRINT(@sql);
-- post-processing
SELECT @sql +=
CONCAT
(
')'
,@crlf
,'SELECT InMemDatabases.*, sys.databases.log_reuse_wait_desc'
,@crlf
,'FROM InMemDatabases '
,@crlf
,'INNER JOIN sys.databases ON '
,'QUOTENAME(sys.databases.name) = InMemDatabases.databaseName;'
);
IF @debug = 1
PRINT('--Determine which databases are memory-optimized' + @crlf + @sql + @crlf);
DECLARE @RowCount INT = (SELECT COUNT(*) FROM #inmemDatabases);
IF @RowCount <> 0
BEGIN
IF OBJECT_ID('tempdb..#MemoryOptimizedDatabases') IS NOT NULL DROP TABLE #MemoryOptimizedDatabases;
CREATE TABLE #MemoryOptimizedDatabases
(
rowNumber INT IDENTITY
, dbName NVARCHAR(256) NOT NULL
, database_id INT NULL
, log_reuse_wait_desc NVARCHAR(256)
);
INSERT #MemoryOptimizedDatabases
(
dbName
,database_id
,log_reuse_wait_desc
)
EXECUTE sp_executesql @sql;
--IF @debug = 1 PRINT(@sql + @crlf);
--ELSE
--BEGIN
SELECT 'Memory-optimized database(s)' AS databases
,dbName
,database_id
,log_reuse_wait_desc
FROM #MemoryOptimizedDatabases
ORDER BY dbName;
--END;
END;
IF OBJECT_ID('tempdb..#NativeModules') IS NOT NULL DROP TABLE #NativeModules;
CREATE TABLE #NativeModules
(
moduleKey INT IDENTITY NOT NULL
,moduleID INT NOT NULL
,moduleName NVARCHAR(256) NOT NULL
,collectionStatus BIT NULL
);
SELECT @sql = '';
DECLARE @dbCounter INT = 1;
SELECT @MaxRows = COUNT(*) FROM #MemoryOptimizedDatabases;
DECLARE @databaseID INT = 1;
/*
###################################################
This is the loop that processes each db
###################################################
*/
WHILE @dbCounter <= @MaxRows
BEGIN
SELECT 'now processing database: ' + dbName AS Status
FROM #MemoryOptimizedDatabases
WHERE rowNumber = @dbCounter;
/*
###################################################
List memory-optimized tables in this database
###################################################
*/
SELECT @sql =
CONCAT
(
'SELECT '
,'''Memory optimized tables'''
, ' AS [object],'
, ' N'''
,dbName
,''' AS databaseName'
,', b.name AS tableName
, p.rows AS [rowCount]
,durability_desc '
,CASE WHEN @Version >= 13 THEN ', temporal_type_desc ' ELSE ',NULL AS temporal_type_desc' END
,', FORMAT(memory_allocated_for_table_kb, ''###,###,###'') AS memoryAllocatedForTableKB
,FORMAT(memory_used_by_table_kb, ''###,###,###'') AS memoryUsedByTableKB
,FORMAT(memory_allocated_for_indexes_kb, ''###,###,###'') AS memoryAllocatedForIndexesKB
,FORMAT(memory_used_by_indexes_kb, ''###,###,###'') AS memoryUsedByIndexesKB
FROM '
, dbName
,'.sys.dm_db_xtp_table_memory_stats a'
,' INNER JOIN '
, dbName
,'.sys.tables b ON b.object_id = a.object_id'
,' INNER JOIN '
,dbName
,'.sys.partitions p'
,' ON p.[object_id] = b.[object_id]'
,' INNER JOIN '
,dbName
,'.sys.schemas s'
,' ON b.[schema_id] = s.[schema_id]'
,' WHERE p.index_id = 2'
)
FROM #MemoryOptimizedDatabases
WHERE rowNumber = @dbCounter;
IF @tableName IS NOT NULL
BEGIN
SELECT @sql += CONCAT(' AND b.name = ', '''', @tableName, '''');
END;
IF @debug = 1
PRINT('--List memory-optimized tables in this database' + @crlf + @sql + @crlf);
ELSE
BEGIN
DELETE @resultsInMemTables
INSERT @resultsInMemTables
EXECUTE sp_executesql @sql;
IF EXISTS(SELECT 1 FROM @resultsInMemTables)
SELECT * FROM @resultsInMemTables;
END;
/*
##############################################################
List indexes on memory-optimized tables in this database
##############################################################
*/
SELECT @sql =
CONCAT
(
'SELECT '
,'''List indexes on memory-optimized tables in this database'' AS [object],'
,' N'''
,dbName
,''''
,' AS databaseName
,t.name AS tableName
,i.name AS indexName
,c.memory_consumer_id
,c.memory_consumer_type_desc AS consumerType
,c.memory_consumer_desc AS description
,c.allocation_count AS allocations
,FORMAT(c.allocated_bytes / 1024.0, ''###,###,###,###'') AS allocatedBytesMB
,FORMAT(c.used_bytes / 1024.00, ''###,###,###,###.###'') AS usedBytesMB
FROM '
,dbName
,'.sys.dm_db_xtp_memory_consumers c
INNER JOIN '
,dbName
,'.sys.tables t ON t.object_id = c.object_id'
,CASE WHEN @Version > 12 THEN ' INNER JOIN sys.memory_optimized_tables_internal_attributes a ON a.object_id = c.object_id
AND a.xtp_object_id = c.xtp_object_id' ELSE NULL END
,@crlf + ' LEFT JOIN '
,dbName
,'.sys.indexes i ON c.object_id = i.object_id
AND c.index_id = i.index_id '
,CASE WHEN @Version > 12 THEN 'AND a.minor_id = 0' ELSE NULL END
,@crlf + ' WHERE t.type = '
, '''u'''
, ' AND t.is_memory_optimized = 1 '
,' AND i.index_id IS NOT NULL'
)
FROM #MemoryOptimizedDatabases
WHERE rowNumber = @dbCounter;
IF @tableName IS NOT NULL
BEGIN
SELECT @sql += CONCAT(' AND t.name = ', '''', @tableName, '''');
END;
SELECT @sql += ' ORDER BY tableName, indexName;'
IF @debug = 1
PRINT('--List indexes on memory-optimized tables in this database' + @crlf + @sql + @crlf);
ELSE
BEGIN
DELETE @resultsIndexes
INSERT @resultsIndexes
EXECUTE sp_executesql @sql;
IF EXISTS(SELECT 1 FROM @resultsIndexes)
SELECT * FROM @resultsIndexes;
END;
/*
#########################################################
verify avg_chain_length for HASH indexes
From BOL:
Empty buckets:
33% is a good target value, but a larger percentage (even 90%) is usually fine.
When the bucket count equals the number of distinct key values, approximately 33% of the buckets are empty.
A value below 10% is too low.
Chains within buckets:
An average chain length of 1 is ideal in case there are no duplicate index key values. Chain lengths up to 10 are usually acceptable.
If the average chain length is greater than 10, and the empty bucket percent is greater than 10%,
the data has so many duplicates that a hash index might not be the most appropriate type.
#########################################################
*/
SELECT @sql =
CONCAT
(
'SELECT '
,'''avg_chain_length for HASH indexes'''
,' AS [object],'''
,dbName
,''''
,' AS databaseName'
,', sch.name AS [Schema] '
,', t.name AS tableName
,i.name AS [indexName]
,h.total_bucket_count AS totalBucketCount
,h.empty_bucket_count AS emptyBucketCount
,FLOOR((CAST(h.empty_bucket_count AS FLOAT) / h.total_bucket_count) * 100) AS [emptybBucketPercent]
,h.avg_chain_length AS avg_ChainLength
,h.max_chain_length AS maxChainLength
,IIF(FLOOR((CAST(h.empty_bucket_count AS FLOAT) / h.total_bucket_count) * 100) < 33, ''Free buckets % is low!'', '''') AS [Free buckets status]
,IIF(h.avg_chain_length > 10 AND FLOOR((CAST(h.empty_bucket_count AS FLOAT) / h.total_bucket_count) * 100) > 10, ''avg_chain_length has many collisions!'', '''') AS [avg_chain_length status]
FROM '
,dbName
,'.sys.dm_db_xtp_hash_index_stats AS h
INNER JOIN '
,dbName
,'.sys.indexes AS i ON h.object_id = i.object_id AND h.index_id = i.index_id'
,CASE WHEN @Version > 12 THEN
CONCAT(' INNER JOIN ', dbName ,'.sys.memory_optimized_tables_internal_attributes ia ON h.xtp_object_id = ia.xtp_object_id') ELSE NULL END
,' INNER JOIN '
,dbName
,'.sys.tables t ON h.object_id = t.object_id'
,' INNER JOIN '
,dbName
,'.sys.schemas sch ON sch.schema_id = t.schema_id '
,CASE WHEN @Version > 12 THEN 'WHERE ia.type = 1' ELSE NULL END
)
FROM #MemoryOptimizedDatabases
WHERE rowNumber = @dbCounter;
IF @tableName IS NOT NULL
BEGIN
SELECT @sql += CONCAT(' AND t.name = ', '''', @tableName, '''');
END;
SELECT @sql += ' ORDER BY sch.name
,t.name
,i.name;';
IF @debug = 1
PRINT('--Verify avg_chain_length for HASH indexes' + @crlf + @sql + @crlf);
ELSE
BEGIN
DELETE @resultsHashBuckets
INSERT @resultsHashBuckets
EXECUTE sp_executesql @sql;
;
IF EXISTS(SELECT 1 FROM @resultsHashBuckets)
SELECT * FROM @resultsHashBuckets;
END;
/*
#########################################################
Count of indexes per table in this database
#########################################################
*/
SELECT @sql =
CONCAT
(
'SELECT '
,'''Number of indexes per table'' AS [object],'
,' N'''
,dbName
,''''
,' AS databaseName
,t.name AS tableName
,COUNT(DISTINCT i.index_id) AS indexCount
FROM '
,dbName
,'.sys.dm_db_xtp_memory_consumers c
INNER JOIN '
,dbName
,'.sys.tables t ON t.object_id = c.object_id'
,CASE WHEN @Version > 12 THEN
CONCAT(' INNER JOIN ', dbName ,'.sys.memory_optimized_tables_internal_attributes a ON a.object_id = c.object_id
AND a.xtp_object_id = c.xtp_object_id') ELSE NULL END
,' LEFT JOIN '
,dbName
,'.sys.indexes i ON c.object_id = i.object_id
AND c.index_id = i.index_id '
,CASE WHEN @Version > 12 THEN ' AND a.minor_id = 0' ELSE NULL END
,' WHERE t.type = '
, '''u'''
, ' AND t.is_memory_optimized = 1 '
,' AND i.index_id IS NOT NULL'
--,' GROUP BY t.name
-- ORDER BY t.name'
)
FROM #MemoryOptimizedDatabases
WHERE rowNumber = @dbCounter;
IF @tableName IS NOT NULL
BEGIN
SELECT @sql += CONCAT(' AND t.name = ', '''', @tableName, '''');
END;
SELECT @sql +=
' GROUP BY t.name
ORDER BY t.name';
IF @debug = 1
PRINT('--Count of indexes per table in this database' + @crlf + @sql + @crlf);
ELSE
BEGIN
DELETE @resultsIndexCount
INSERT @resultsIndexCount
EXECUTE sp_executesql @sql;
IF EXISTS(SELECT 1 FROM @resultsIndexCount)
SELECT * FROM @resultsIndexCount;
END;
/*
#####################################################
List natively compiled modules in this database
#####################################################
*/
/*
FN = SQL scalar function
IF = SQL inline table-valued function
TF = SQL table-valued-function
TR = SQL DML trigger
*/
IF @tableName IS NULL
BEGIN
SELECT @sql =
CONCAT
(
'SELECT ''Natively compiled modules'' AS [object],'
,' N'''
,dbName
,''''
,' AS databaseName
,A.name
,CASE A.type
WHEN ''FN'' THEN ''Function''
WHEN ''P'' THEN ''Procedure''
WHEN ''TR'' THEN ''Trigger''
END AS type
,B.definition AS [definition]
FROM '
, dbName
,'.sys.all_objects AS A
INNER JOIN '
,dbName
,'.sys.sql_modules AS B ON B.object_id = A.object_id
WHERE UPPER(B.definition) LIKE ''%NATIVE_COMPILATION%''
AND UPPER(A.name) <> ''SP_BLITZINMEMORYOLTP''
ORDER BY A.type, A.name'
)
FROM #MemoryOptimizedDatabases
WHERE rowNumber = @dbCounter;
IF @debug = 1
PRINT('--List natively compiled modules in this database' + @crlf + @sql + @crlf);
ELSE
BEGIN
DELETE @resultsNativeModules
INSERT @resultsNativeModules
EXECUTE sp_executesql @sql;
IF EXISTS(SELECT 1 FROM @resultsNativeModules)
SELECT * FROM @resultsNativeModules;
END;
END;
/*
#####################################################
List *loaded* natively compiled modules in this database, i.e. executed at least 1x
#####################################################
*/
/*
the format for checkpoint files changed from SQL 2014 to SQL 2016
SQL 2014 format:
database_id = 5
object_id = 309576141
H:\SQLDATA\xtp\5\xtp_p_5_309576141.dll
SQL 2016+ format
database_id = 9
object_id = 1600880920