Rebuild Index of a database table

DECLARE @Database VARCHAR(255)
DECLARE @Table VARCHAR(255)
DECLARE @cmd NVARCHAR(500)

DECLARE @fillfactor INT
SET @fillfactor = 90

CREATE Table #databaseName (dbid int identity(1,1), DbName Varchar(255))

Insert into #databaseName
SELECT name
FROM   MASTER.dbo.sysdatabases
—  WHERE  name NOT IN ( ‘master’, ‘model’, ‘msdb’, ‘tempdb’, ‘distrbution’ )
WHERE  name IN ( ‘OD’)
ORDER  BY 1

CREATE Table #TableName (Tableid int identity(1,1), TableName Varchar(1000))

declare @DbCnt int
declare @TblCnt int
declare @i int
declare @j int

select @i = 1
select @j = 1

select @DbCnt = Max(dbid) from #databaseName

WHILE @i <= @Dbcnt
BEGIN
SELECT @cmd = ‘Insert Into #TableName SELECT table_catalog + ”.” + table_schema + ”.” + table_name as tableName
FROM ‘ + DbName + ‘.INFORMATION_SCHEMA.TABLES WHERE table_type = ”BASE TABLE”’
from #databaseName where dbid = @i

— create table cursor
Print @cmd
EXEC (@cmd)

select @tblCnt = Max(Tableid) from #tableName

WHILE @j <= @tblcnt
BEGIN
— SQL 2000 command
–DBCC DBREINDEX(@Table,’ ‘,@fillfactor)
— SQL 2005 command
SELECT @cmd = ‘ALTER INDEX ALL ON ‘ + TableName + ‘ REBUILD WITH (FILLFACTOR = ‘ + Convert(VARCHAR(3), @fillfactor) + ‘)’
From #tableName where Tableid = @j

print @cmd
EXEC (@cmd)

Set @j =@j + 1
END

Set @i =@i + 1

END

drop table #databaseName
drop table #tableName

Author: Arvind Singh

Microsoft Dynamics CRM Consultant

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s