How to use MSSQL, rebuild all indexes on all tables? MSSQL Server 2008
Solution 1:
You could probably write a script that uses dynamic SQL to do that, but why do that when you can use someone else's? Ola Hallengren's are the best known and free, but Minion Ware also has a free reindex script.
If you insist on writing it yourself, something like this might work:
Use mssqlDB01
Declare @TBname nvarchar(255),
@schema nvarchar(255),
@SQL nvarchar(max)
select @TBname = min(TABLE_NAME) from INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
select @schema = SCHEMA_NAME from INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' and TABLE_NAME = @TBname
while @TBname is not null
BEGIN
set @SQL='ALTER INDEX ALL ON [' + @schema + '].[' + @TBname + '] REBUILD;'
--print @SQL
EXEC SP_EXECUTESQL @SQL
select @TBname = min(TABLE_NAME) from INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
select @schema = SCHEMA_NAME from INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' and TABLE_NAME = @TBname
END
Solution 2:
- Press Ctrl + T
Run this query:
SELECT 'ALTER INDEX ALL ON ' + table_name + ' REBUILD;' FROM Information_Schema.tables where table_type ='BASE TABLE'
Copy the output and paste it into the SQL window, then click on run.
Solution 3:
Building on @Firdaus nice and simple answer:
If your database has schemas, try running the following in SSMS:
SELECT 'ALTER INDEX ALL ON ' + TABLE_SCHEMA + '.' + table_name + ' REBUILD;'
FROM Information_Schema.tables where table_type ='BASE TABLE'