-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_analysis.sql
More file actions
242 lines (241 loc) · 7.75 KB
/
Copy pathheap_analysis.sql
File metadata and controls
242 lines (241 loc) · 7.75 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
/*******************************************************************************
Script Name: heap_analysis.sql
Purpose: Finds heap tables and evaluates their size, forwarded records, page density, extent fragmentation, and nonclustered indexes. Physical statistics are collected using SAMPLED mode.
Scope: Current database
SQL Server: 2016+
Azure SQL: Azure SQL Database and Managed Instance; see docs/COMPATIBILITY.md
Permissions: Metadata visibility; physical-statistics scripts require VIEW DATABASE STATE
Risk: Read-only; potentially high query cost because physical statistics use SAMPLED mode.
Output: Priority, Category, Object, Finding, Evidence, Recommendation, SuggestedSql, Risk
Author: TheMax-Lab
Version: 1.0
License: MIT
*******************************************************************************/
;WITH HeapSize AS
(
SELECT
dps.object_id,
SUM(CONVERT(bigint, dps.row_count)) AS RowCount,
SUM(CONVERT(bigint, dps.reserved_page_count)) AS ReservedPageCount,
SUM(CONVERT(bigint, dps.used_page_count)) AS UsedPageCount
FROM sys.dm_db_partition_stats AS dps
WHERE dps.index_id = 0
GROUP BY
dps.object_id
)
SELECT
CASE
WHEN
(
COALESCE(ph.ForwardedRecords, 0) >= 100000
OR
(
COALESCE(ph.ForwardedRecords, 0) >= 1000
AND metrics.ForwardedPercent >= 5.00
)
)
THEN 'High'
ELSE 'Medium'
END AS [Priority],
'Schema' AS [Category],
CONCAT
(
QUOTENAME(s.name),
'.',
QUOTENAME(t.name)
) AS [Object],
CASE
WHEN COALESCE(ph.ForwardedRecords, 0) > 0 THEN
'Heap contains forwarded records'
WHEN hs.ReservedPageCount >= 12800
OR hs.RowCount >= 1000000 THEN
'Large table is stored as a heap'
ELSE
'Table is stored as a heap'
END AS [Finding],
CONCAT
(
'rows=', hs.RowCount,
'; reserved MB=',
CONVERT
(
decimal(18,2),
CONVERT(float, hs.ReservedPageCount) * 8.0 / 1024.0
),
'; used MB=',
CONVERT
(
decimal(18,2),
CONVERT(float, hs.UsedPageCount) * 8.0 / 1024.0
),
'; nonclustered indexes=',
COALESCE(ni.NonclusteredIndexCount, 0),
'; forwarded rows=',
COALESCE(ph.ForwardedRecords, 0),
'; forwarded percent=',
metrics.ForwardedPercent,
'; average page density percent=',
COALESCE
(
CONVERT
(
varchar(30),
CONVERT(decimal(9,2), ph.AveragePageDensityPercent)
),
'n/a'
),
'; extent fragmentation percent=',
COALESCE
(
CONVERT
(
varchar(30),
CONVERT(decimal(9,2), ph.ExtentFragmentationPercent)
),
'n/a'
),
'; physical stats mode=SAMPLED'
) AS [Evidence],
CASE
WHEN COALESCE(ph.ForwardedRecords, 0) > 0 THEN
'Review variable-length updates and row growth. Test a heap rebuild as a short-term correction. Consider a clustered index only when access patterns and a suitable clustering key justify it.'
WHEN hs.ReservedPageCount >= 12800
OR hs.RowCount >= 1000000 THEN
'Evaluate table access patterns, range queries, lookup frequency, ETL behavior, and candidate clustering keys. A heap can be intentional, but large heaps should have a documented design rationale.'
ELSE
'Confirm that heap storage is intentional. Small staging, queue, or transient tables can be valid heaps; monitor growth and forwarded records.'
END AS [Recommendation],
CASE
WHEN COALESCE(ph.ForwardedRecords, 0) > 0 THEN
CONCAT
(
'-- Test duration, blocking, log usage, and required free space before execution.',
CHAR(13),
CHAR(10),
'ALTER TABLE ',
QUOTENAME(s.name),
'.',
QUOTENAME(t.name),
' REBUILD;'
)
ELSE
'-- No automatic change recommended. A clustered key cannot be selected safely without workload and data analysis.'
END AS [SuggestedSql],
'High: rebuilding a heap or creating a clustered index can require substantial log and temporary space, block concurrent activity, and rebuild nonclustered indexes because row locators change.' AS [Risk]
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON s.schema_id = t.schema_id
INNER JOIN sys.indexes AS heap_index
ON heap_index.object_id = t.object_id
AND heap_index.index_id = 0
INNER JOIN HeapSize AS hs
ON hs.object_id = t.object_id
OUTER APPLY
(
SELECT
SUM
(
CONVERT
(
bigint,
COALESCE(ips.forwarded_record_count, 0)
)
) AS ForwardedRecords,
SUM
(
CASE
WHEN ips.avg_page_space_used_in_percent IS NOT NULL THEN
CONVERT(float, ips.avg_page_space_used_in_percent)
* CONVERT(float, ips.page_count)
END
)
/
NULLIF
(
SUM
(
CASE
WHEN ips.avg_page_space_used_in_percent IS NOT NULL THEN
CONVERT(float, ips.page_count)
END
),
0.0
) AS AveragePageDensityPercent,
SUM
(
CASE
WHEN ips.avg_fragmentation_in_percent IS NOT NULL THEN
CONVERT(float, ips.avg_fragmentation_in_percent)
* CONVERT(float, ips.page_count)
END
)
/
NULLIF
(
SUM
(
CASE
WHEN ips.avg_fragmentation_in_percent IS NOT NULL THEN
CONVERT(float, ips.page_count)
END
),
0.0
) AS ExtentFragmentationPercent
FROM sys.dm_db_index_physical_stats
(
DB_ID(),
t.object_id,
0,
NULL,
'SAMPLED'
) AS ips
WHERE ips.index_id = 0
AND ips.index_level = 0
AND ips.alloc_unit_type_desc = 'IN_ROW_DATA'
) AS ph
OUTER APPLY
(
SELECT
COUNT(*) AS NonclusteredIndexCount
FROM sys.indexes AS i
WHERE i.object_id = t.object_id
AND i.index_id > 0
AND i.is_hypothetical = 0
) AS ni
CROSS APPLY
(
VALUES
(
CONVERT
(
decimal(9,2),
COALESCE
(
100.0
* CONVERT(float, COALESCE(ph.ForwardedRecords, 0))
/ NULLIF(CONVERT(float, hs.RowCount), 0.0),
0.0
)
)
)
) AS metrics(ForwardedPercent)
WHERE t.is_ms_shipped = 0
AND t.is_memory_optimized = 0
ORDER BY
CASE
WHEN
(
COALESCE(ph.ForwardedRecords, 0) >= 100000
OR
(
COALESCE(ph.ForwardedRecords, 0) >= 1000
AND metrics.ForwardedPercent >= 5.00
)
)
THEN 0
ELSE 1
END,
COALESCE(ph.ForwardedRecords, 0) DESC,
hs.ReservedPageCount DESC,
s.name,
t.name;