Friday, 2 November 2018

Script to Rebuild all Indexes of a Database




In below script, I commented Fill Factor related changes, and If anyone wants, they uncomment it.
Please SELECT your database and execute the below script.

Note: Database REBUILD INDEX is a very costly operation and It requires an exclusive lock on table
so please aware yourself before executing it.

DECLARE @DatabaseName SYSNAME   = DB_NAME()
DECLARE @TableName VARCHAR(256) 
--DECLARE @FILLFACTOR INT = 85
DECLARE @SQL NVARCHAR(MAX) =

 'DECLARE curAllIndex CURSOR FOR SELECT TABLE_SCHEMA +
 ''.'' + TABLE_NAME AS TABLENAME  
 FROM ' + @DatabaseName + '.INFORMATION_SCHEMA.TABLES WHERE
 TABLE_TYPE = ''BASE TABLE'''  

BEGIN 
  EXEC sp_executeSQL @SQL  
  OPEN curAllIndex
  FETCH NEXT FROM curAllIndex INTO @TableName  
  WHILE (@@FETCH_STATUS = 0) 
  BEGIN  
       /* -- For using FillFactor setting. 
   SET @DynamicSQL = 'ALTER INDEX ALL ON ' + @TableName +  
   ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR,@FILLFACTOR) + ')' 
   */
   SET @SQL = 'ALTER INDEX ALL ON ' + @TableName +  
   ' REBUILD ' 
       PRINT @SQL       
       EXEC sp_executeSQL @SQL 
       FETCH NEXT FROM curAllIndex INTO @TableName  
   END   
   CLOSE curAllIndex  
   DEALLOCATE curAllIndex 
END


Happy coding !!!

No comments:

Post a Comment

SQL Audits

1. sys.server_audits What it is: Lists all server-level audit objects . An audit is the top-level object that defines: Where to wri...