Skip to content

Instantly share code, notes, and snippets.

@Romiko
Created May 13, 2014 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Romiko/e56a7c8002700d2a22b9 to your computer and use it in GitHub Desktop.
Save Romiko/e56a7c8002700d2a22b9 to your computer and use it in GitHub Desktop.
Rebuild Indexes
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET NOCOUNT ON
GO
IF (OBJECT_ID('RebuildIndexes') IS NOT NULL)
DROP PROCEDURE RebuildIndexes
GO
CREATE procedure [dbo].[RebuildIndexes]
(
@DatabaseName VARCHAR(255),
@ExcludeTables VARCHAR(MAX) = '''AUDIT'',''AUDIT2'''
)
as
DECLARE @Database VARCHAR(255)
DECLARE @Table VARCHAR(255)
DECLARE @cmd NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 75
DECLARE DatabaseCursor CURSOR FOR
SELECT name FROM master.dbo.sysdatabases
WHERE name IN (@DatabaseName)
ORDER BY 1
OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd = 'DECLARE TableCursor CURSOR FOR SELECT table_catalog + ''.'' + table_schema + ''.'' + table_name as tableName
FROM ' + @Database + '.INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'' AND table_name not in (' + @ExcludeTables + ') '
EXEC (@cmd)
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN
print 'Rebuilding ' + @Table
declare @start datetime = Getdate()
Select @Table = Substring(@table, 0, LEN(@table) - PATINDEX('%.%',REVERSE(@table)) + 2) + '[' +
SUBSTRING(@table, LEN(@table) - PATINDEX('%.%', REVERSE(@table)) + 2,LEN(@table)) + ']'
SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD WITH (FILLFACTOR = ' +CONVERT(VARCHAR(3),@fillfactor) + ', ONLINE = OFF)' --ON for enterprise edition with try catch to switch to offline
EXEC (@cmd)
WAITFOR DELAY '0:00:05';
print 'Completed Rebuilding ' + @Table + ' Elapsed Time in seconds: ' + CONVERT(VARCHAR(200), DATEDIFF(ss,@start,getdate()))
FETCH NEXT FROM TableCursor INTO @Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment