Can anyone provide the script for rebuilding and re-indexing the fragmented index when 'avg_fragmentation_in_percent' exceeds certain limits (better if cursor is not used)?
Can anyone provide the script for rebuilding and re-indexing the fragmented index when 'avg_fragmentation_in_percent' exceeds certain limits (better if cursor is not used)?
6条答案
按热度按时间ttcibm8c1#
To rebuild use:
or to reorganize use:
Reorganizing should be used at lower (<30%) fragmentations but only rebuilding (which is heavier to the database) cuts the fragmentation down to 0%.
For further information see https://msdn.microsoft.com/en-us/library/ms189858.aspx
41zrol4v2#
Two solutions: One simple and one more advanced.
Introduction
There are two solutions available to you depending on the severity of your issue
Replace with your own values, as follows:
XXXMYINDEXXXX
with the name of an index.XXXMYTABLEXXX
with the name of a table.XXXDATABASENAMEXXX
with the name of a database.Solution 1. Indexing
Rebuild all indexes for a table in offline mode
Rebuild one specified index for a table in offline mode
Solution 2. Fragmentation
Fragmentation is an issue in tables that regularly have entries both added and removed.
Check fragmentation percentage
Fragmentation 5..30%
If the fragmentation value is greater than 5%, but less than 30% then it is worth reorganising indexes.
Reorganise all indexes for a table
Reorganise one specified index for a table
Fragmentation 30%+
If the fragmentation value is 30% or greater then it is worth rebuilding then indexes in online mode.
Rebuild all indexes in online mode for a table
Rebuild one specified index in online mode for a table
bqujaahr3#
Query for REBUILD/REORGANIZE Indexes
Query:
Output
mqkwyuun4#
Here is the modified script which i took from http://www.foliotek.com/devblog/sql-server-optimization-with-index-rebuilding which i found useful to post here. Although it uses a cursor and i know what is the main problem with cursors it can be easily converted to a cursor-less version.
It is well-documented and you can easily read through it and modify to your needs.
qvk1mo1f5#
The real answer, in 2016 and 2017, is: Use Ola Hallengren's scripts:
https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html
That is all any of us need to know or bother with, at this point in our mutual evolution.
snz8szmq6#
I have found the following script is very good at maintaining indexes, you can have this scheduled to run nightly or whatever other timeframe you wish.
http://sqlfool.com/2011/06/index-defrag-script-v4-1/