{"id":72,"date":"2010-11-30T15:57:57","date_gmt":"2010-11-30T22:57:57","guid":{"rendered":"http:\/\/www.sqldbpros.com\/?p=72"},"modified":"2012-12-06T16:29:09","modified_gmt":"2012-12-06T23:29:09","slug":"sql-server-rebuild-indexes-the-fastest-way","status":"publish","type":"post","link":"http:\/\/sqldbpros.com\/wordpress\/2010\/11\/sql-server-rebuild-indexes-the-fastest-way\/","title":{"rendered":"SQL Server Rebuild Indexes &#8211; The Fastest Way"},"content":{"rendered":"<p>Want to rebuild all the indexes in your MS SQL database?\u00a0 The script below will rebuild all the indexes in your SQL Server 2008 or SQL Server 2005 (SP2) database and offers a number of enhancements that make this the best SQL Server index rebuild script in all the land and the first choice of SQL Server consultants:<\/p>\n<ol>\n<li>Rebuilds indexes on smallest tables first, allowing the maximum number of indexes to be rebuilt in the shortest amount of time.<\/li>\n<li>Real time progress updates, allowing you to estimate how much time is remaining before completion.<\/li>\n<li>Correctly handles multiple schemas, a common flaw in other scripts.<\/li>\n<\/ol>\n<p><!--more--><\/p>\n<blockquote><p>SET NOCOUNT ON<br \/>\nGO<\/p>\n<p>--Set the fillfactor<br \/>\nDECLARE @FillFactor TINYINT<br \/>\nSELECT @FillFactor=80<\/p>\n<p>DECLARE @StartTime DATETIME<br \/>\nSELECT @StartTime=GETDATE()<\/p>\n<p>if object_id('tempdb..#TablesToRebuildIndex') is not null<br \/>\nbegin<br \/>\ndrop table #TablesToRebuildIndex<br \/>\nend<\/p>\n<p>DECLARE @NumTables VARCHAR(20)<\/p>\n<p>SELECT<br \/>\ns.[Name] AS SchemaName,<br \/>\nt.[name] AS TableName,<br \/>\nSUM(p.rows) AS RowsInTable<br \/>\nINTO #TablesToRebuildIndex<br \/>\nFROM<br \/>\nsys.schemas s<br \/>\nLEFT JOIN sys.tables t<br \/>\nON\u00a0 s.schema_id = t.schema_id<br \/>\nLEFT JOIN sys.partitions p<br \/>\nON\u00a0 t.object_id = p.object_id<br \/>\nLEFT JOIN sys.allocation_units a<br \/>\nON\u00a0 p.partition_id = a.container_id<br \/>\nWHERE<br \/>\np.index_id IN ( 0, 1 ) -- 0 heap table , 1 table with clustered index<br \/>\nAND p.rows IS NOT NULL<br \/>\nAND a.type = 1\u00a0 -- row-data only , not LOB<br \/>\nGROUP BY<br \/>\ns.[Name],<br \/>\nt.[name]<br \/>\nSELECT @NumTables=@@ROWCOUNT<\/p>\n<p>DECLARE RebuildIndex CURSOR FOR<br \/>\nSELECT<br \/>\nROW_NUMBER() OVER (ORDER BY ttus.RowsInTable),<br \/>\nttus.SchemaName,<br \/>\nttus.TableName,<br \/>\nttus.RowsInTable<br \/>\nFROM<br \/>\n#TablesToRebuildIndex AS ttus<br \/>\nORDER BY<br \/>\nttus.RowsInTable<br \/>\nOPEN RebuildIndex<\/p>\n<p>DECLARE @TableNumber VARCHAR(20)<br \/>\nDECLARE @SchemaName NVARCHAR(128)<br \/>\nDECLARE @tableName NVARCHAR(128)<br \/>\nDECLARE @RowsInTable VARCHAR(20)<br \/>\nDECLARE @Statement NVARCHAR(300)<br \/>\nDECLARE @Status NVARCHAR(300)<\/p>\n<p>FETCH NEXT FROM RebuildIndex INTO @TableNumber, @SchemaName, @tablename, @RowsInTable<br \/>\nWHILE ( @@FETCH_STATUS = 0 )<br \/>\nBEGIN<br \/>\nSET @Status='Table '+@TableNumber+' of '+@NumTables+': Rebuilding indexes on '+@SchemaName+'.'+@tablename + ' ('+@RowsInTable+' rows)'<br \/>\nRAISERROR (@Status, 0, 1) WITH NOWAIT\u00a0 --RAISERROR used to immediately output status<\/p>\n<p>SET @Statement = 'ALTER INDEX ALL ON ['+@SchemaName+'].['+@tablename +'] REBUILD WITH (FILLFACTOR = '+CONVERT(VARCHAR(3), @FillFactor)+' )'<br \/>\nEXEC sp_executesql @Statement<\/p>\n<p>FETCH NEXT FROM RebuildIndex INTO @TableNumber, @SchemaName, @tablename, @RowsInTable<br \/>\nEND<\/p>\n<p>CLOSE RebuildIndex<br \/>\nDEALLOCATE RebuildIndex<\/p>\n<p>drop table #TablesToRebuildIndex<\/p>\n<p>Print 'Total Elapsed Time: '+CONVERT(VARCHAR(100), DATEDIFF(minute, @StartTime, GETDATE()))+' minutes'<\/p>\n<p>GO<\/p>\n<p>&nbsp;<\/p><\/blockquote>\n<p>A quick followup based on the comment from Jack Smith. There is no need to specify ALLOW_PAGE_LOCKS=ON since it is actually the default for SQL Server 2005 through SQL Server 2012 (per <a href=\"http:\/\/technet.microsoft.com\/en-us\/library\/ms188388%28v=sql.110%29.aspx\" target=\"_blank\">MSDN ALTER INDEX Transact-SQL<\/a> article).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Want to rebuild all the indexes in your MS SQL database?\u00a0 The script below will rebuild all the indexes in your SQL Server 2008 or SQL Server 2005 (SP2) database and offers a number of enhancements that make this the best SQL Server index rebuild script in all the land and the first choice of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,3],"tags":[13,10,4,9,12,11],"class_list":["post-72","post","type-post","status-publish","format-standard","hentry","category-performance-tuning","category-scripts","tag-indexes","tag-ms-sql","tag-performance","tag-sql-server","tag-sql-server-2005","tag-sql-server-2008"],"_links":{"self":[{"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/posts\/72","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/comments?post=72"}],"version-history":[{"count":7,"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/posts\/72\/revisions"}],"predecessor-version":[{"id":348,"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/posts\/72\/revisions\/348"}],"wp:attachment":[{"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/media?parent=72"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/categories?post=72"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/sqldbpros.com\/wordpress\/wp-json\/wp\/v2\/tags?post=72"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}