T-SQL re-indexing all tables in all databases

Source: Internet
Author: User
Declare @ database varchar (255) Declare @ sqlcmd varchar (1000) Declare @ test bitset @ test = 1 declare databasecursor cursor forward_only read_only forselect name from Master. DBO. sysdatabases where name not in ('master', 'model', 'msdb', 'tempdb', 'distrbution ', 'reportserver', 'reportservertempdb ') open databasecursor fetch next from databasecursor into @ database while @ fetch_status = 0 begin set @ sqlcmd = 'use '+ @ Database +'; if exists (select 1 from sys. dm_db_index_physical_stats (db_id (), null, ''detailled'') indexstats where indexstats. avg_fragmentation_in_percent> 25) beginexec sp_msforeachtable @ command1 = ''alter index all on? Rebuild ''' + 'print ''' indexes rebuild successfully on database' + @ database + '! ''End'' if @ test = 1 beginselect @ sqlcmdendelsebeginexec (@ sqlcmd) endfetch next from databasecursor into @ database endclose databasecursor deallocate databasecursor

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.