/
Management.GatherIndexUsageStatistics.sql
296 lines (274 loc) · 8.98 KB
/
Management.GatherIndexUsageStatistics.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
/************************************************************************************************
Index Usage Statistics
By Wesley D. Brown
Date 06/27/2011
**Description**
This procedure pulls back critical index information on usage patters and general index
information like index size. From this information you can determine if an index is
actually in use by your system.
Functions:
**End Discription**
**Change Log**
Bug Fix: altered table creation to conform with standard information schema checking
**End Change Log**
************************************************************************************************/
/************************************************************************************************
DROP TABLE dbo.IndexUsageStatistics
DROP TABLE dbo.IndexUsageStatisticsHistory
************************************************************************************************/
IF NOT EXISTS (SELECT *
FROM dbo.sysobjects
WHERE id = Object_id(N'[dbo].[IndexUsageStatistics]')
AND Objectproperty(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE dbo.IndexUsageStatistics(
ServerName nvarchar(128),
DBName nvarchar(128),
SchemaName nvarchar(128),
TableName nvarchar(128),
IndexName nvarchar(128),
IsUsed bit,
IsExpensive bit,
TypeDescription nvarchar(60),
UserReads bigint,
UserWrites bigint,
Reads bigint,
LeafWrites bigint,
LeafPageSplits bigint,
NonleafWrites bigint,
NonleafPageSplits bigint,
UserSeeks bigint,
UserScans bigint,
UserLookups bigint,
UserUpdates bigint,
LastUserSeek datetime,
LastUserScan datetime,
LastUserLookup datetime,
LastUserUpdate datetime,
RecordCount bigint,
TotalPageCount bigint,
IndexSizeInMegabytes float,
AverageRecordSizeInBytes float,
IndexDepth int,
RecordedDateTime datetime
)
END
ELSE
BEGIN
PRINT 'Table IndexUsageStatistics already exists'
END
IF NOT EXISTS (SELECT *
FROM dbo.sysobjects
WHERE id = Object_id(N'[dbo].[IndexUsageStatisticsHistory]')
AND Objectproperty(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE dbo.IndexUsageStatisticsHistory(
ServerName nvarchar(128),
DBName nvarchar(128),
SchemaName nvarchar(128),
TableName nvarchar(128),
IndexName nvarchar(128),
IsUsed bit,
IsExpensive bit,
TypeDescription nvarchar(60),
UserReads bigint,
UserWrites bigint,
Reads bigint,
LeafWrites bigint,
LeafPageSplits bigint,
NonleafWrites bigint,
NonleafPageSplits bigint,
UserSeeks bigint,
UserScans bigint,
UserLookups bigint,
UserUpdates bigint,
LastUserSeek datetime,
LastUserScan datetime,
LastUserLookup datetime,
LastUserUpdate datetime,
RecordCount bigint,
TotalPageCount bigint,
IndexSizeInMegabytes float,
AverageRecordSizeInBytes float,
IndexDepth int,
RecordedDateTime datetime
)
END
ELSE
BEGIN
PRINT 'Table IndexUsageStatisticsHistory already exists'
END
IF EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.ROUTINES
WHERE SPECIFIC_NAME = N'GatherIndexUsageStatistics'
)
DROP PROCEDURE GatherIndexUsageStatistics
GO
/*
exec GatherIndexUsageStatistics 'ALL',1
select * from IndexUsageStatistics
*/
CREATE PROCEDURE GatherIndexUsageStatistics
@DatabaseList VARCHAR(MAX),
@ExcludeSystemDatabases tinyint = 1
AS
SET NOCOUNT ON
/*****************************************
* Truncate holding tables
*****************************************/
IF EXISTS (SELECT 1
FROM dbo.IndexUsageStatistics)
BEGIN
INSERT INTO dbo.IndexUsageStatisticsHistory
SELECT *
FROM dbo.IndexUsageStatistics;
TRUNCATE TABLE dbo.IndexUsageStatistics;
END
DECLARE @cmd VARCHAR(8000),
@servername VARCHAR(256),
@dbname VARCHAR(256),
@recordeddatetime datetime
CREATE TABLE #dbnames
(
name NVARCHAR(128)
)
SET @recordeddatetime = GETDATE()
SET @servername = CAST(Serverproperty('servername') AS VARCHAR(256))
IF Upper(@DatabaseList) = 'ALL'
BEGIN
IF @ExcludeSystemDatabases = 1
BEGIN
SET @DatabaseList = '';
SELECT @DatabaseList = @DatabaseList + '''' + name + ''','
FROM MASTER.dbo.sysdatabases
WHERE name NOT IN ( 'master', 'msdb', 'model', 'pubs',
'northwind', 'tempdb' );
END
ELSE
BEGIN
SELECT @DatabaseList = @DatabaseList + '''' + name + ''','
FROM MASTER.dbo.sysdatabases;
END
SET @DatabaseList = LEFT(@DatabaseList, Len(@DatabaseList) - 2) + ''''
INSERT INTO #dbnames
EXEC('select name from master.dbo.sysdatabases where name in ('+@DatabaseList+')')
END
--found at http://mangalpardeshi.blogspot.com/2009/03/how-to-split-comma-delimited-string.html
;WITH Cte AS
(
select CAST('<M>' + REPLACE( @DatabaseList, ',' , '</M><M>') + '</M>' AS XML) AS DatabaseNames
)
insert into #dbnames
SELECT
Split.a.value('.', 'VARCHAR(100)') AS DatabaseNames
FROM Cte
CROSS APPLY DatabaseNames.nodes('/M') Split(a)
IF not exists(select 1 from #dbnames)
BEGIN
insert into #dbnames select @DatabaseList
END
DECLARE db CURSOR FAST_FORWARD FOR
SELECT name
FROM #dbnames
OPEN db
FETCH NEXT FROM db INTO @dbname
WHILE ( @@FETCH_STATUS <> -1 )
BEGIN
IF ( @@FETCH_STATUS <> -2 )
BEGIN
IF (SELECT CONVERT(SYSNAME, Databasepropertyex(@dbname, 'status'))
)
=
'ONLINE'
BEGIN
set @cmd ='
INSERT INTO dbo.IndexUsageStatistics
SELECT *
,'''+convert(varchar,@recordeddatetime, 121)+'''
FROM (SELECT '''+@servername+''' AS ''ServerName'',
'''+@dbname+''' AS ''DBName'',
Object_schema_name(so.object_id,DB_ID('''+@dbname+''')) as ''SchemaName'',
OBJECT_NAME(so.object_id,db_id('''+@dbname+''')) as ''TableName'',
i.name AS ''IndexName'',
Convert(BIT,CASE
WHEN u.object_id IS NULL
THEN 0
ELSE 1
END) as ''IsUsed'',
Convert(BIT,CASE
WHEN (i.type_desc <> ''HEAP''
AND (leaf_insert_count
+ leaf_update_count
+ leaf_delete_count) > (range_scan_count
+ singleton_lookup_count))
THEN 1
ELSE 0
END) as ''IsExpensive'',
i.type_desc,
u.user_seeks
+ u.user_scans
+ u.user_lookups as ''UserReads'',
u.user_updates as ''UserWrites'',
Reads = range_scan_count
+ singleton_lookup_count,
leaf_insert_count
+ leaf_update_count
+ leaf_delete_count as''LeafWrites'',
leaf_allocation_count as ''LeafPageSplits'',
nonleaf_insert_count
+ nonleaf_update_count
+ nonleaf_delete_count as ''NonleafWrites'',
nonleaf_allocation_count as ''NonleafPageSplits'',
u.user_seeks,
u.user_scans,
u.user_lookups,
u.user_updates,
u.last_user_seek,
u.last_user_scan,
u.last_user_lookup,
u.last_user_update,
f.record_count,
f.page_count,
f.IndexSizeInMegabytes,
f.AverageRecordSizeInBytes,
f.IndexDepth
FROM ['+@dbname+'].sys.indexes i
INNER JOIN ['+@dbname+'].sys.objects so
ON so.object_id = i.object_id
INNER JOIN (SELECT object_id,
index_id,
Sum(record_count) AS record_count,
Sum(page_count) AS page_count,
Convert(FLOAT,Sum(page_count))
* 8192
/ 1024
/ 1024 AS ''IndexSizeInMegabytes'',
Avg(avg_record_size_in_bytes) AS ''AverageRecordSizeInBytes'',
Sum(index_depth) AS ''IndexDepth''
FROM sys.Dm_db_index_physical_stats(DB_ID('''+@dbname+'''),NULL,NULL,NULL,''SAMPLED'') f
GROUP BY object_id,
index_id) f
ON i.object_id = f.object_id
AND i.index_id = f.index_id
LEFT JOIN ['+@dbname+'].sys.dm_db_index_usage_stats u
ON f.object_id = u.object_id
AND f.index_id = u.index_id
AND u.database_id = DB_ID('''+@dbname+''')
INNER JOIN sys.Dm_db_index_operational_stats(DB_ID('''+@dbname+'''),NULL,NULL,NULL) s
ON i.object_id = s.object_id
AND i.index_id = s.index_id
WHERE so.TYPE = ''U''
) indexes
ORDER BY
TableName,
IndexName'
EXEC(@cmd)
END
END
FETCH NEXT FROM db INTO @dbname
END
CLOSE db
DEALLOCATE db
DROP TABLE #dbnames
SET nocount OFF