Code: Rebuild Indexes for a list of tables
Use below code and make necessary modifications to make it work as per your needs. I am extremely sorry that I couldn’t test below code. It was just scripted and forwarded to my colleague to test and deploy the code.
/*Perform a 'USE ' to select
the database in which to run the script.*/ -- Create the table. IF OBJECT_ID('tempdb..##fragstatus') IS NOT NULL DROP table ##fragstatus; CREATE TABLE ##fragstatus ( table_name varchar(100), index_name varchar(100) ) -- Declare variables SET NOCOUNT ON; DECLARE @tablename varchar(255); DECLARE @execstr varchar(400); DECLARE @objectid int; DECLARE @indexid int; DECLARE @frag decimal; DECLARE @indexname varchar(255); /*TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT*/ -- Declare a cursor. DECLARE tables CURSOR FOR SELECT tablename FROM fragmentedtablelist /*Table name for table list*/ -- Open the cursor. OPEN tables; -- Loop through all the tables in the above list. FETCH NEXT FROM tables INTO @tablename; WHILE @@FETCH_STATUS = 0 BEGIN; /*ttttttttttttttttttttttttttttttt*/ DECLARE indexes CURSOR for SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID(@tablename) open indexes; FETCH NEXT from indexes into @indexname while @@FETCH_STATUS = 0 BEGIN ---Execute Index Rebuild. SELECT @execstr = 'ALTER INDEX [' + @indexname +'] ON [' + REPLACE(@tablename,'.','].[') + '] REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = ON)'; exec (@execstr); INSERT INTO ##fragstatus --USE THIS TABLE TO VIEW THE ACTIVITY PROGRESS VALUES (@tablename, @indexname); FETCH NEXT FROM indexes into @indexname END close indexes; deallocate indexes; /*ttttttttttttttttttttttttttttttt*/ FETCH NEXT FROM tables INTO @tablename; END; -- Close and deallocate the cursor. CLOSE tables; DEALLOCATE tables; /*TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT*/ select * from ##fragstatus PRINT 'Defrag/rebuild completed';