Rebuild All Indexes in a Database

Another instance of the the basic cursor shell in action.

if exists (select * from sysobjects where id=object_id('dbo.mysp_reindex') 
                                    and sysstat & 0xf = 4)
	drop procedure dbo.mysp_reindex
GO

/* ?bills Cursor Shell v2
   --Rebuild Indexes-- 
   create a cursor against sysobjects and perform a repetitive operation
   against the current database. */
create procedure mysp_reindex
as
 DECLARE @procedure varchar(50), 
	 @fillfactor varchar(3),
         @objectname varchar(30), 
	 @type varchar(2),
	 @database varchar(30),
	 @completion_message varchar(50) 	

 set nocount on
 
 select @procedure = "DBCC DBREINDEX (" -- do not include trailing space	
 select @fillfactor = "80"
 select @type = "U" 
 select @completion_message = "All indexes have been rebuilt in database"	

 select @database = (select name from master..sysdatabases 
	             where dbid = (select dbid from master..sysprocesses
	     		           where spid = @@SPID))
 

 select "Start Time", getdate()

 DECLARE object_cursor CURSOR
   FOR
   SELECT name FROM sysobjects 
   WHERE type = @type 
   order by name
 OPEN object_cursor
   FETCH NEXT FROM object_cursor INTO @objectname
   WHILE (@@fetch_status <> -1)
     BEGIN
       select @procedure = "DBCC DBREINDEX (" + @objectname
       select @procedure = @procedure + ", ''," + @fillfactor + ")"
       select @procedure = @procedure + " WITH NO_INFOMSGS"	
       print @objectname 
       EXECUTE (@procedure)
       FETCH NEXT FROM object_cursor INTO @objectname
     END
 DEALLOCATE object_cursor
 select @completion_message = @completion_message + @database
 print ""
 select @completion_message, getdate()
 set nocount off

GO