Advertisement
PtiTom

MaintenanceIndex

Jul 2nd, 2013
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.40 KB | None | 0 0
  1. SET ANSI_NULLS ON
  2. GO
  3. SET QUOTED_IDENTIFIER ON
  4. GO
  5.  
  6. CREATE PROCEDURE MaintenanceIndex
  7. AS
  8. BEGIN
  9.     SET NOCOUNT ON
  10.     DECLARE @sInstruction NVARCHAR(MAX)
  11.     SELECT @sInstruction = N'SELECT * INTO ##FragmentedIndexes FROM ('
  12.  
  13.     SELECT
  14.         @sInstruction = @sInstruction + N' SELECT N''' + s.name + '.' + t.name + ''' AS TargetTable, name AS TargetIndex, N''ALTER INDEX '' + name + N'' ON ' + s.name + '.' + t.name + ' ''
  15.             + CASE WHEN avg_fragmentation_in_percent > 30 THEN ''REBUILD'' ELSE ''REORGANIZE'' END as ExecuteMe
  16.             FROM sys.dm_db_index_physical_stats (DB_ID(), OBJECT_ID(N''' + s.name + N'.' + t.name + N'''), NULL, NULL, NULL) AS a JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id WHERE avg_fragmentation_in_percent > 5 AND name IS NOT NULL UNION ALL'
  17.     FROM
  18.         sys.tables T
  19.         JOIN sys.schemas S ON S.schema_id = T.schema_id
  20.  
  21.     SELECT @sInstruction = @sInstruction + N' SELECT N'''', N'''', N'''' WHERE 0 = 1) AS T'
  22.  
  23.     EXEC (@sInstruction)
  24.     SELECT * FROM ##FragmentedIndexes
  25.  
  26.     SELECT @sInstruction = N''
  27.     SELECT @sInstruction = @sInstruction + '
  28.     ' + ExecuteMe FROM ##FragmentedIndexes
  29.  
  30.     --SELECT @sInstruction
  31.     EXEC (@sInstruction)
  32.  
  33.     DROP TABLE ##FragmentedIndexes
  34.  
  35.     -- Shrink des logs.
  36.     SELECT @sInstruction = N''
  37.     SELECT @sInstruction = @sInstruction + N'
  38.     DBCC SHRINKFILE (N''' + name + ''', 0)'
  39.     FROM sysfiles WHERE groupid = 0
  40.  
  41.     EXEC (@sInstruction)
  42. END
  43. GO
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement