Skip to content

Instantly share code, notes, and snippets.

@MarshalOfficial
Created October 21, 2015 12:22
Show Gist options
  • Save MarshalOfficial/4e803c594d9dbb40cbd1 to your computer and use it in GitHub Desktop.
Save MarshalOfficial/4e803c594d9dbb40cbd1 to your computer and use it in GitHub Desktop.
Rebuild All Indexes In Database
DECLARE @Database VARCHAR(255)
DECLARE @Table VARCHAR(255)
DECLARE @cmd NVARCHAR(500)
DECLARE @fillfactor INT
DECLARE @DBName VARCHAR(100)
select @DBName = 'DBName'
SET @fillfactor = 90
DECLARE DatabaseCursor CURSOR FOR
SELECT name FROM master.dbo.sysdatabases
WHERE name = @DBName
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'''
-- create table cursor
EXEC (@cmd)
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@@MICROSOFTVERSION / POWER(2, 24) >= 9)
BEGIN
-- SQL 2005 or higher command
SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
print @cmd
EXEC (@cmd)
END
ELSE
BEGIN
-- SQL 2000 command
DBCC DBREINDEX(@Table,' ',@fillfactor)
END
FETCH NEXT FROM TableCursor INTO @Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
DBCC SHRINKDATABASE(@DBName)
GO
--So what is the ideal fill factor? It depends on the ratio of reads to writes that your application makes to your SQL Server tables. As a rule of thumb, follow these guidelines:
-- Low Update Tables (100-1 read to write ratio): 100% fill factor
-- High Update Tables (where writes exceed reads): 50%-70% fill factor
-- Everything In-Between: 80%-90% fill factor.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment