Search

Monday, November 21, 2011

Rebuild all indexes for all tables and all databases

Below is script to rebuild all indexes for all tables of all Databases. In this script I had used two cursor, one for Table and other for Database. In this script I had excluded system Databases. You can exclude some other database also in the same way.


DECLARE @DB_Name VARCHAR(255)   
DECLARE @Table_Name VARCHAR(255)  
DECLARE @Command NVARCHAR(500)  
DECLARE @FillFactor INT 


SET @FillFactor = 90 


DECLARE DBCursor CURSOR FOR  
SELECT Name FROM MASTER.dbo.SysDatabases   
WHERE Name NOT IN ('master','msdb','tempdb','model','distribution')   
ORDER BY 1  


OPEN DBCursor  


FETCH NEXT FROM DBCursor INTO @DB_Name  
WHILE @@FETCH_STATUS = 0  
BEGIN  


   SET @Command = 'DECLARE TableCursor CURSOR FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' + 
  table_name + '']'' as tableName FROM ' + @DB_Name + '.INFORMATION_SCHEMA.TABLES 
  WHERE table_type = ''BASE TABLE'''   


   -- create table cursor  
   EXEC (@Command)  
   OPEN TableCursor   


   FETCH NEXT FROM TableCursor INTO @Table_Name   
   WHILE @@FETCH_STATUS = 0   
   BEGIN   


       IF (@@MICROSOFTVERSION / POWER(2, 24) >= 9)
       BEGIN
           -- SQL 2005 or higher command 
           SET @Command = 'ALTER INDEX ALL ON ' + @Table_Name + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@FillFactor) + ')' 
           EXEC (@Command) 
       END
       ELSE
       BEGIN
          -- SQL 2000 command 
          DBCC DBREINDEX(@Table_Name,' ',@FillFactor)  
       END


       FETCH NEXT FROM TableCursor INTO @Table_Name   
   END   


   CLOSE TableCursor   
   DEALLOCATE TableCursor  


   FETCH NEXT FROM DBCursor INTO @DB_Name  
END  
CLOSE DBCursor   
DEALLOCATE DBCursor

No comments:

Post a Comment