Created
June 19, 2018 23:00
-
-
Save ivaneftimov/1a94607a83da674d92644f8966c6b7b4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Rebuild SF DB indexes | |
| DECLARE @dbName nvarchar(100) | |
| SET @dbName = N'YourDatabaseName'; | |
| DECLARE @useStatement nvarchar(110) | |
| SET @useStatement = N'USE ' + @dbName + '; ' | |
| --PRINT @useStatement | |
| EXEC (@useStatement) | |
| SET NOCOUNT ON; | |
| DECLARE @objectid int; | |
| DECLARE @indexid int; | |
| DECLARE @partitioncount bigint; | |
| DECLARE @schemaname nvarchar(130); | |
| DECLARE @objectname nvarchar(130); | |
| DECLARE @indexname nvarchar(130); | |
| DECLARE @partitionnum bigint; | |
| DECLARE @partitions bigint; | |
| DECLARE @frag float; | |
| DECLARE @command nvarchar(4000); | |
| SELECT | |
| object_id AS objectid, | |
| index_id AS indexid, | |
| partition_number AS partitionnum, | |
| avg_fragmentation_in_percent AS frag | |
| INTO #doit2 | |
| FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') | |
| WHERE index_id > 0; | |
| DECLARE partitions CURSOR FOR SELECT * FROM #doit2; | |
| OPEN partitions; | |
| WHILE (1=1) | |
| BEGIN; | |
| FETCH NEXT | |
| FROM partitions | |
| INTO @objectid, @indexid, @partitionnum, @frag; | |
| IF @@FETCH_STATUS < 0 BREAK; | |
| SELECT @objectname = QUOTENAME(o.name), @schemaname = QUOTENAME(s.name) | |
| FROM sys.objects AS o | |
| JOIN sys.schemas as s ON s.schema_id = o.schema_id | |
| WHERE o.object_id = @objectid AND (o.name!='QueryNotificationErrorsQueue' AND o.Name!='EventNotificationErrorsQueue' AND o.Name!='ServiceBrokerQueue'); | |
| SELECT @indexname = QUOTENAME(name) | |
| FROM sys.indexes | |
| WHERE object_id = @objectid AND index_id = @indexid; | |
| SELECT @partitioncount = count (*) | |
| FROM sys.partitions | |
| WHERE object_id = @objectid AND index_id = @indexid; | |
| SET @command = @useStatement | |
| SET @command = @command + N' | |
| ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + | |
| N' REBUILD WITH (FILLFACTOR = 90, SORT_IN_TEMPDB = ON) '; | |
| IF @partitioncount > 1 | |
| SET @command = @command + N' PARTITION=' + CAST(@partitionnum AS nvarchar(10)); | |
| EXEC sp_ExecuteSQL @command; | |
| PRINT N'Executed: ' + @command; | |
| SET @command = @useStatement | |
| SET @command = @command + ' | |
| UPDATE STATISTICS ' + @schemaname + N'.' + @objectname + ';' | |
| EXEC sp_ExecuteSQL @command | |
| PRINT N'Executed: ' + @command; | |
| END; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment