Two Hoots Banner



Reindex all User tables in the current database

The following stored procedure reindexes all user tables in the current database.

CREATE PROCEDURE sp_AdminReindexTables
AS
BEGIN 

declare @continue	integer,
	@TableCounter	integer,
	@string		varchar(80),
	@TableName	varchar(50),
	@SQL		varchar (255)

set nocount on 

declare curTable cursor

for SELECT name
 FROM 		sysobjects
 WHERE 		type = 'U'
 order by	name
 for read only

-- open cursor
open curTable

select 	
@continue	= 1,
@TableCounter	= 0,
@string		= ""

while 	(@continue = 1)
begin
 fetch 	next from curTable
	into 	@TableName

 if (@@FETCH_STATUS <> 0)
  begin
   --fetch failed; end loop
   select @continue = 0
   break
  end	--if fetchstatus <> 0
 else	-- continue next table
  begin
   --successful fetch
   select @TableCounter = @TableCounter + 1
   -- DBCC DBREINDEX (authors, '', 70)
   select @SQL = "DBCC DBREINDEX (" + @TableName + ", '', 70) "
   exec (@SQL)
  end	-- else successful fetch
end --while (@continue = 1)

-- final cleanup
close curTable
deallocate curTable

select "Total Number of Tables:" = @TableCounter

END

go
Instead of checking to see if you've reached the end of the file, the For loop simply ticks off the appropriate number of cycles. This structure will speed up your search a great deal--as much as 30 percent.