SQL Server Index reconstruction, SQL Server Index
The company's online data has tens of millions of data records. Sometimes index fragmentation may cause indexes to fail to meet our expected query efficiency. At this time, re-indexing will improve the efficiency, however, during reconstruction, there must be fewer users at night, and index reconstruction takes some time.
Paste the automatic index reconstruction script directly.
1 DECLARE @Database VARCHAR(255); 2 DECLARE @Table VARCHAR(255); 3 DECLARE @cmd NVARCHAR(500); 4 DECLARE @fillfactor INT; 5 SET @fillfactor = 90; 6 DECLARE DatabaseCursor CURSOR 7 FOR 8 SELECT name 9 FROM master.dbo.sysdatabases10 WHERE name IN ( 'ChemicalInfo_ALLFULL_New' )11 ORDER BY 1; 12 OPEN DatabaseCursor; 13 FETCH NEXT FROM DatabaseCursor INTO @Database; 14 WHILE @@FETCH_STATUS = 015 BEGIN 16 SET @cmd = 'DECLARE TableCursor CURSOR FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +17 table_name + '']'' as tableName FROM [' + @Database18 + '].INFORMATION_SCHEMA.TABLES19 WHERE table_type = ''BASE TABLE'''; 20 -- create table cursor 21 EXEC (@cmd); 22 OPEN TableCursor; 23 FETCH NEXT FROM TableCursor INTO @Table; 24 WHILE @@FETCH_STATUS = 025 BEGIN 26 IF ( @@MICROSOFTVERSION / POWER(2, 24) >= 9 )27 BEGIN28 -- SQL 2005 or higher command29 SET @cmd = 'ALTER INDEX ALL ON ' + @Table30 + ' REBUILD WITH (FILLFACTOR = '31 + CONVERT(VARCHAR(3), @fillfactor) + ')';32 EXEC (@cmd);33 END;34 ELSE35 BEGIN36 -- SQL 2000 command37 DBCC DBREINDEX(@Table,' ',@fillfactor); 38 END;39 FETCH NEXT FROM TableCursor INTO @Table; 40 END; 41 CLOSE TableCursor; 42 DEALLOCATE TableCursor; 43 FETCH NEXT FROM DatabaseCursor INTO @Database; 44 END; 45 CLOSE DatabaseCursor; 46 DEALLOCATE DatabaseCursor;