Friday, May 28, 2010

Need to rebuild ALL indexes in a database?

Need to rebuild ALL indexes in a database? Recently i used the script below.


set nocount on
declare @totcnt int
, @rowcnt int
, @nsql nvarchar(max)

declare @sql_statements table (
Id int identity(1, 1)
, SqlStatement nvarchar(max)
)

insert
into @sql_statements
select 'alter index ' + i.name + ' on ' + object_name(i.object_id) + ' rebuild '
from sys.indexes i

set @totcnt = @@rowcount
set @rowcnt = 1
while @rowcnt <= @totcnt

begin
  select  @nsql = SqlStatement 

  from    @sql_statements 
  where   Id = @rowcnt 


  exec sp_executesql @nsql 
  set @rowcnt = @rowcnt + 1 
end

For this script i was sure that i had to rebuild them, in stead of reorganizing them. I will post some tips about the usage of rebuilding vs reorganizing anytime soon

No comments:

Post a Comment