Advertisement
Xabier-Clemente

SpDefragmentIndexes

Oct 29th, 2021
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.77 KB | None | 0 0
  1. /* IMPORTANT: Be sure to save this document on WordPad or other text-editors with a ".sql" extension */
  2.  
  3. /****** Object: StoredProcedure [dbo].[SpDefragmentIndexes] Script Date: 4/19/2021 12:21:57 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6.  
  7. SET QUOTED_IDENTIFIER ON
  8. GO
  9.  
  10. /*---------------------------------------------------------------------------*/
  11. /* This procedure reorganizes and rebuilds the index if the fragmentation */
  12. /* level is higher the given threshold. You can set the threshold for */
  13. /* reorganize as well as for rebuild and script will work accordingly */
  14. /* Parameters: */
  15. /* @FragmentationThresholdForReorganizeTableLowerLimit - Fragmentation Level */
  16. /* lower threshold to check for reorganizing the table, if the fragmentation */
  17. /* is higher than this level, it will be considered for reorganize. */
  18. /* @FragmentationThresholdForRebuildTableLowerLimit - Fragmentation Level */
  19. /* lower threshold to check for rebuilding the table, if the fragmentation is*/
  20. /* higher than this level, it will be considered for rebuild. */
  21. /* NOTES: Print statements are all queued up and don't show up until the */
  22. /* entire script is printed. However, there is an alternative to Printing */
  23. /* messages. */
  24. /* You can raise an error that isn't really an error (code of 0) and you'll */
  25. /* get the same effect--message will be printed immediately. */
  26. /*---------------------------------------------------------------------------*/
  27. ALTER PROC [dbo].[SpDefragmentIndexes](@FragmentationThresholdForReorganizeTableLowerLimit varchar(10), @FragmentationThresholdForRebuildTableLowerLimit varchar(10))
  28. AS
  29. DECLARE @cmd nvarchar(1000)
  30. DECLARE @Table varchar(255)
  31. DECLARE @SchemaName varchar(255)
  32. DECLARE @IndexName varchar(255)
  33. DECLARE @AvgFragmentationInPercent decimal
  34. DECLARE @fillfactor int
  35. DECLARE @minFactor decimal
  36. DECLARE @maxFactor decimal
  37. DECLARE @tempFactor decimal
  38.  
  39. SET NOCOUNT ON
  40.  
  41. SET @fillfactor = 90
  42.  
  43. -- Factors for Rebuilding/Reorganizing the Index; Make sure both are
  44. -- between 10, 100 % */
  45. SET @minFactor = 10.0
  46. SET @maxFactor = 100.0
  47.  
  48. -- Rebuild Limit
  49. SET @tempFactor = CONVERT(decimal, @FragmentationThresholdForRebuildTableLowerLimit)
  50. IF @tempFactor < @minFactor SET @tempFactor = @minFactor
  51. ELSE IF @tempFactor > @maxFactor SET @tempFactor = @maxFactor
  52. SET @FragmentationThresholdForRebuildTableLowerLimit = CONVERT(varchar(10), @tempFactor)
  53.  
  54. -- Reorganize Limit
  55. SET @tempFactor = CONVERT(decimal, @FragmentationThresholdForReorganizeTableLowerLimit)
  56. IF @tempFactor < @minFactor SET @tempFactor = @minFactor
  57. ELSE IF @tempFactor > @maxFactor SET @tempFactor = @maxFactor
  58. SET @FragmentationThresholdForReorganizeTableLowerLimit = CONVERT(varchar(10), @tempFactor)
  59.  
  60. -- Ensure the temporary table does not exist
  61. IF (SELECT OBJECT_ID('tempdb..#FragmentedTableList')) IS NOT NULL
  62. DROP TABLE #FragmentedTableList;
  63.  
  64. SELECT OBJECT_NAME(IPS.OBJECT_ID) AS [TableName], avg_fragmentation_in_percent, SI.name [IndexName],
  65. schema_name(ST.schema_id) AS [SchemaName], 0 AS IsProcessed into #FragmentedTableList
  66. FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL , NULL) IPS
  67. JOIN sys.tables ST WITH (nolock) ON IPS.OBJECT_ID = ST.OBJECT_ID
  68. JOIN sys.indexes SI WITH (nolock) ON IPS.OBJECT_ID = SI.OBJECT_ID AND IPS.index_id = SI.index_id
  69. WHERE ST.is_ms_shipped = 0 AND SI.name IS NOT NULL
  70. AND avg_fragmentation_in_percent >= CONVERT(decimal, @FragmentationThresholdForReorganizeTableLowerLimit)
  71. ORDER BY avg_fragmentation_in_percent DESC
  72.  
  73.  
  74. WHILE EXISTS ( SELECT 1 FROM #FragmentedTableList WHERE IsProcessed = 0 )
  75. BEGIN
  76.  
  77. SELECT TOP 1 @Table = TableName, @AvgFragmentationInPercent = avg_fragmentation_in_percent,
  78. @SchemaName = SchemaName, @IndexName = IndexName
  79. FROM #FragmentedTableList
  80. WHERE IsProcessed = 0
  81.  
  82. --Reorganizing the index
  83. IF((@AvgFragmentationInPercent >= @FragmentationThresholdForReorganizeTableLowerLimit) AND (@AvgFragmentationInPercent < @FragmentationThresholdForRebuildTableLowerLimit))
  84. BEGIN
  85. SET @cmd = 'ALTER INDEX [' + @IndexName + '] ON [' + RTRIM(LTRIM(@SchemaName)) + '].[' + RTRIM(LTRIM(@Table)) + '] REORGANIZE'
  86. EXEC (@cmd)
  87. --Print @cmd
  88. END
  89. --Rebuilding the index
  90. ELSE IF (@AvgFragmentationInPercent >= @FragmentationThresholdForRebuildTableLowerLimit )
  91. BEGIN
  92. SET @cmd = 'ALTER INDEX [' + @IndexName + '] ON [' + RTRIM(LTRIM(@SchemaName)) + '].[' + RTRIM(LTRIM(@Table)) + '] REBUILD WITH (FILLFACTOR = ' + CONVERT(varchar(3),@fillfactor) + ', STATISTICS_NORECOMPUTE = OFF)'
  93. EXEC (@cmd)
  94. --Print @cmd
  95. END
  96.  
  97. UPDATE #FragmentedTableList SET IsProcessed = 1 WHERE TableName = @Table AND IndexName = @IndexName
  98. END
  99.  
  100. DROP TABLE #FragmentedTableList
  101. GO
  102.  
  103.  
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement