
Explanation to Defragment All Indexes in a Database
In this detail how to generate and run a SQL Server script that could automatically identify and repair index fragmentation of all indexes within a database. Index fragmentation which is caused by the frequent updates of data can extensively result in the poor performance of a database. This granted by the script given isolates the degree of fragmentation, and re-ordering (in the case of low fragmentation) or recreates (in the case of high fragmentation) the indexes in order to attain the optimal level of performance.
Over time, indexes in SQL Server become fragmented due to frequent INSERT
, UPDATE
, or DELETE
operations. Fragmentation reduces performance by increasing disk I/O. To improve performance, indexes should be reorganized (if mildly fragmented) or rebuilt (if heavily fragmented).
You can use a script to automatically detect and fix fragmentation for all indexes in a database.
Example Script:
- DECLARE @TableName NVARCHAR(128);
- DECLARE @SQL NVARCHAR(MAX);
- -- Cursor to go through each table
- DECLARE TableCursor CURSOR FOR
- SELECT QUOTENAME(SCHEMA_NAME(o.schema_id)) + '.' + QUOTENAME(o.name)
- FROM sys.objects o
- WHERE o.type = 'U';
- OPEN TableCursor;
- FETCH NEXT FROM TableCursor INTO @TableName;
- WHILE @@FETCH_STATUS = 0
- BEGIN
- SET @SQL = '
- DECLARE @IndexName NVARCHAR(128);
- DECLARE @IndexId INT;
- DECLARE @Frag FLOAT;
- SELECT @IndexId = index_id,
- @Frag = avg_fragmentation_in_percent
- FROM sys.dm_db_index_physical_stats (DB_ID(), OBJECT_ID(''' + @TableName + '''), NULL, NULL, ''LIMITED'')
- WHERE index_id > 0;
- IF @Frag > 30
- ALTER INDEX ALL ON ' + @TableName + ' REBUILD;
- ELSE IF @Frag > 5
- ALTER INDEX ALL ON ' + @TableName + ' REORGANIZE;
- ';
- EXEC sp_executesql @SQL;
- FETCH NEXT FROM TableCursor INTO @TableName;
- END
- CLOSE TableCursor;
- DEALLOCATE TableCursor;
1.Variable Declaration
- @TableName: It stores the name of the table, which is being worked on.
- @SQL: The SQL command generated dynamically is stored.
- @TableName: It stores the name of the table, which is being worked on.
- @SQL: The SQL command generated dynamically is stored.
2. Cursor Creation
A new cursor called Table Cursor is defined which will be used to traverse all the user tables of the database. - SELECT statement retrieves the schema name and the name of user tables.
- QUOTENAME ensures that the schema and table names are quoted in a proper manner and at this, names containing special characters are given the right treatment.
- SELECT statement retrieves the schema name and the name of user tables.
- QUOTENAME ensures that the schema and table names are quoted in a proper manner and at this, names containing special characters are given the right treatment.
3. Cursor Iteration
- Cursor is opened and the initial name of table is loaded into the variable @TableName.
- The WHILE loop runs until further tables need to be processed (@@FETCH_STATUS = 0).
- Cursor is opened and the initial name of table is loaded into the variable @TableName.
- The WHILE loop runs until further tables need to be processed (@@FETCH_STATUS = 0).
4. Dynamic SQL Generation of SQL.
Inside the loop, the script creates a dynamic SQL statement and puts it in charge of the variable @SQL.In this dynamic SQL statement, it does the following:- Declares variables to hold index information: @IndexName, @IndexId and @Frag.
- Executes a call to the dynamic management function (DMF), sys.dm_db_index_physical_stats, in order to see the fragmentation percentage (avg_fragmentation_in_percent) of each single index in the current table. Faster execution is described as limited sampling mode.
- Verifies the percentage of fragmentation (@Frag) and ascertains the need to execute either a REBUILD or a REORGANIZE operation:
- @Frag > 30 will result in the running of the statement ALTER INDEX ALL on + @TableName + rebuild; in the script. This reconstitutes every index on the table. Rebuilding uses more resources but it is more suited to heavily fragmented indexes.
- In case @Frag > 5, the script will run the ALTER INDEX ALL ON ' + @TableName + ' REORGANIZE;. This reorganizes all indexes on a table. One is reorganizing, an light operation that performs well on indexes that are moderately fragmented.
- Declares variables to hold index information: @IndexName, @IndexId and @Frag.
- Executes a call to the dynamic management function (DMF), sys.dm_db_index_physical_stats, in order to see the fragmentation percentage (avg_fragmentation_in_percent) of each single index in the current table. Faster execution is described as limited sampling mode.
- Verifies the percentage of fragmentation (@Frag) and ascertains the need to execute either a REBUILD or a REORGANIZE operation:
- @Frag > 30 will result in the running of the statement ALTER INDEX ALL on + @TableName + rebuild; in the script. This reconstitutes every index on the table. Rebuilding uses more resources but it is more suited to heavily fragmented indexes.
- In case @Frag > 5, the script will run the ALTER INDEX ALL ON ' + @TableName + ' REORGANIZE;. This reorganizes all indexes on a table. One is reorganizing, an light operation that performs well on indexes that are moderately fragmented.
5. Execution of Dynamic SQL
The dynamic SQL statement in sp_executesql stored procedure executes the saved SQL text in @SQL. This allows script to optimize index maintenance depending on the extent of fragmentation of an index.
6. Cursor Management
• Once the dynamic SQL is executed, the script pulls the next table name in cursor and loads in the variable @TableName.• After all the tables are done, a cursor is closed and deallocated to free system resources.
Explanation of Logic:
-
> 30% fragmentation →
REBUILDING
an index, drops the current index and recreates it. It is more efficient when indexes are very fragmented and it is more resources-demanding, therefore it is also slower.5%–30% fragmentation →
REORGANIZE
the Index Reorganizing of an index implies that the particular leaf-nodes are reordered to reflect the logical order of the index. This is a lightweight operation, which can be conducted online and which is applicable on indexes that are moderately fragmented.< 5% fragmentation → less than 5 % 0 action required Low fragmented indexes are those that cannot be maintained.
Conclusion:
This script is a routine that index-repair, on an automatic basis, all the indexes within a database according to their level of fragmentation. The frequent utilization of this script will facilitate queries to be faster and occupy less space on the hard drive. We should like to arrange the script such that it executes during off-peak time or on a weekly maintenance schedule such that it does not load the database to a crawl.
Post Comment
Your email address will not be published. Required fields are marked *