Script to rebuild all table indexes in the SQL Server
Following is the script which will get all the table names from sys.tables and execute the rebuild index on all the tables in one go for the selected database.
--- Script to rebuild the all the indexes of the database.
declare @name varchar(100),@cmd varchar(200)
declare cn cursor for
select SCHEMA_NAME(schema_id)+'].['+name as "name" from sys.tables where type = 'U';
open cn
fetch cn into @name
while @@fetch_status = 0
begin
set @cmd = 'alter index all on [' + @name + '] rebuild'
print @cmd
exec (@cmd )
fetch cn into @name
end
close cn
deallocate cn
Output:
