Commit 27d2ee4
sp_IndexCleanup: stage dm_db_index_usage_stats to avoid repeated DMV scans
The LEFT JOIN to dm_db_index_usage_stats was executed via nested loops,
scanning the full DMV per row (52M actual rows, ~4 minutes). Now
pre-stages the DMV for the current database into #usage_stats with a
clustered PK on (object_id, index_id) before the main query, then
LEFT JOINs to the temp table instead.
Handles the database cursor loop with TRUNCATE on re-entry.
Tested on SQL2022 (StackOverflow2013) and SQL2016 (StackOverflow2010).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>1 parent ddbbe5c commit 27d2ee4
1 file changed
Lines changed: 53 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2117 | 2117 | | |
2118 | 2118 | | |
2119 | 2119 | | |
| 2120 | + | |
| 2121 | + | |
| 2122 | + | |
| 2123 | + | |
| 2124 | + | |
| 2125 | + | |
| 2126 | + | |
| 2127 | + | |
| 2128 | + | |
| 2129 | + | |
| 2130 | + | |
| 2131 | + | |
| 2132 | + | |
| 2133 | + | |
| 2134 | + | |
| 2135 | + | |
| 2136 | + | |
| 2137 | + | |
| 2138 | + | |
| 2139 | + | |
| 2140 | + | |
| 2141 | + | |
| 2142 | + | |
| 2143 | + | |
| 2144 | + | |
| 2145 | + | |
| 2146 | + | |
| 2147 | + | |
| 2148 | + | |
| 2149 | + | |
| 2150 | + | |
| 2151 | + | |
| 2152 | + | |
| 2153 | + | |
| 2154 | + | |
| 2155 | + | |
| 2156 | + | |
| 2157 | + | |
| 2158 | + | |
| 2159 | + | |
| 2160 | + | |
| 2161 | + | |
| 2162 | + | |
| 2163 | + | |
| 2164 | + | |
| 2165 | + | |
| 2166 | + | |
| 2167 | + | |
| 2168 | + | |
| 2169 | + | |
| 2170 | + | |
| 2171 | + | |
2120 | 2172 | | |
2121 | 2173 | | |
2122 | 2174 | | |
| |||
2238 | 2290 | | |
2239 | 2291 | | |
2240 | 2292 | | |
2241 | | - | |
| 2293 | + | |
2242 | 2294 | | |
2243 | 2295 | | |
2244 | | - | |
2245 | 2296 | | |
2246 | 2297 | | |
2247 | 2298 | | |
| |||
0 commit comments