I’ve found two scripts on how to rebuild or reorganize all indexes in a specific database:
http://geekswithblogs.net/robz/archive/2009/06/09/sql-server-2005-sql-server-2008—rebuild-or-reorganize.aspx
and
http://stackoverflow.com/questions/8326595/how-to-alter-index-for-every-table-in-my-database
But, the thing is that I also wanted a check whether the fragmentation index is higher or lower than 30% (and decide to reorganize or rebuild an index).
So I’ve hustled the script a bit and added a few lines of code and here’s how to execute/use it:
USE []
EXEC [dbo].[usp_Maintenance_RebuildAndReorganizeIndexes] @PreferredSchemaName = 'dbo' --optional input parameter
GO
Click here to download the script (*.docx):
usp_Maintenance_RebuildAndReorganizeIndexes