SQL Server rebuilds the fragmented index automatically

Source: Internet
Author: User
Tags management studio sql server management sql server management studio

1. Is index fragmentation generated?

The index page splits because of a large number of insertions, modifications, and deletions in the table. If the index has a high fragmentation, there are two cases, one is that scanning the index takes a lot of time, and the other is that the index does not use the index at all at the time of the query, which can result in performance degradation.

2. The fragment type is divided into:

2.1 Internal Crushing

Due to data insertion or modification operations in the index page, the data is terminated as a distribution of sparse matrices, resulting in an increase in data pages, which increases query time.

2.2 External crushing

Due to data insertion or modification of index/data pages, ending with page number separation and the allocation of new index pages that are incoherent in the file system, the database server cannot take advantage of the read-ahead operation because: the next associated data page is not near, and the following page numbers for these related links may be anywhere in the data file.

Automatic rebuilding of fragmented indexes

Create a new defragmentation stored procedure in your data

SQL code
  1. -- ================================================
  2. --Template GENERATED from template EXPLORER USING:
  3. --CREATE PROCEDURE (NEW MENU). Sql
  4. --
  5. --Use the Specify VALUES for TEMPLATE PARAMETERS
  6. --COMMAND (CTRL-SHIFT-M) to FILL in the PARAMETER
  7. --VALUES BELOW.
  8. --
  9. --This BLOCK of COMMENTS is not being INCLUDED in
  10. -The DEFINITION of the PROCEDURE.
  11. -- ================================================
  12. SET ANSI_NULLS on
  13. GO
  14. SET QUOTED_IDENTIFIER ON
  15. GO
  16. -- =============================================
  17. --AUTHOR: <AUTHOR,,WUXIANGQIAN>
  18. --CREATE DATE: <create date,2014-05-16>
  19. --DESCRIPTION: <description, rebuilding the fragmented index >
  20. -- =============================================
  21. ALTER PROCEDURE usp_ims_defragment_indexes
  22. As
  23. --Declaring variables
  24. SET NOCOUNT on
  25. DECLARE @TABLENAME VARCHAR (128)-table name (index fragmentation has occurred)
  26. DECLARE @EXECSTR VARCHAR (255)--the statement that performs rebuilding the index
  27. DECLARE @INDEXNAME CHAR (255)--Index name
  28. DECLARE @DBNAME SYSNAME--database name
  29. DECLARE @DBNAMECHAR VARCHAR (20)--Database name
  30. DECLARE @TABLEIDCHAR VARCHAR (255)-table name (for traversing index fragmentation)
  31. --Check whether the user database is running
  32. SELECT @DBNAME = db_name ()
  33. IF @DBNAME in (' Master ', ' msdb ', ' model ', ' tempdb ')
  34. BEGIN
  35. PRINT ' This PROCEDURE should is RUN in SYSTEM DATABASES. '
  36. RETURN
  37. END ELSE
  38. BEGIN
  39. SET @DBNAMECHAR = ' DBNAME '
  40. END
  41. --1th stage: detecting fragments
  42. --Declaring cursors
  43. DECLARE TABLES CURSOR for
  44. SELECT CONVERT (varchar,so.id)
  45. From SYSOBJECTS so
  46. JOIN sysindexes SI
  47. On so.id = Si.id
  48. WHERE so. TYPE = ' U '
  49. and SI. Indid < 2
  50. and SI. ROWS > 0
  51. --Create a temporary table to store fragmentation information
  52. CREATE TABLE #FRAGLIST (
  53. TABLENAME CHAR (255),
  54. IndexName CHAR (255))
  55. --Open cursor
  56. OPEN TABLES
  57. --Executes the DBCC SHOWCONTIG command on all table loops of the database
  58. FETCH NEXT
  59. From TABLES
  60. Into @TABLEIDCHAR
  61. While @ @FETCH_STATUS = 0
  62. BEGIN
  63. --Statistics on all indexes of the table
  64. INSERT into #FRAGLIST
  65. EXEC (' SELECT object_name (DT. OBJECT_ID) as tablename,si.name as IndexName from ' +
  66. ' (SELECT object_id,index_id,avg_fragmentation_in_percent,avg_page_space_used_in_percent ' +
  67. ' From SYS. Dm_db_index_physical_stats (db_id (' [email protected]+ '), object_id (' [email protected]+ ') ' +
  68. ', Null,null, ' detailed ') WHERE index_id<>0) as DT INNER JOIN SYS. INDEXES SI ' +
  69. ' On SI. Object_id=dt. OBJECT_ID and SI. Index_id=dt. index_id and ' +
  70. ' DT. Avg_fragmentation_in_percent>10 ' +
  71. ' and DT. Avg_page_space_used_in_percent<75 ORDER by DT. Avg_fragmentation_in_percent DESC ')
  72. FETCH NEXT
  73. From TABLES
  74. Into @TABLEIDCHAR
  75. END
  76. --Close the release cursor
  77. CLOSE TABLES
  78. Deallocate TABLES
  79. --to check, report statistical results
  80. SELECT * from #FRAGLIST
  81. --2nd Stage: (defragment) declares a cursor for each index to defragment
  82. DECLARE INDEXES CURSOR for
  83. SELECT TABLENAME, IndexName
  84. From #FRAGLIST
  85. --Output start time
  86. SELECT ' STARTED defragmenting INDEXES at ' + CONVERT (varchar,getdate ())
  87. --Open cursor
  88. OPEN INDEXES
  89. --Loop all the indexes
  90. FETCH NEXT
  91. From INDEXES
  92. Into @TABLENAME, @INDEXNAME
  93. While @ @FETCH_STATUS = 0
  94. BEGIN
  95. SET QUOTED_IDENTIFIER ON
  96. SELECT @EXECSTR = ' ALTER INDEX ' [email protected]dexname+ ' on ' [e-mail protected]+ ' REBUILD with (fillfactor=90,online=on )‘
  97. SELECT ' Now executing: '
  98. SELECT (@EXECSTR)
  99. EXEC (@EXECSTR)
  100. SET QUOTED_IDENTIFIER OFF
  101. FETCH NEXT
  102. From INDEXES
  103. Into @TABLENAME, @INDEXNAME
  104. END
  105. --Close the release cursor
  106. CLOSE INDEXES
  107. Deallocate INDEXES
  108. --Report End time
  109. SELECT ' finished defragmenting INDEXES at ' + CONVERT (varchar,getdate ())
  110. --Delete temporary tables
  111. DROP TABLE #FRAGLIST
  112. GO
  113. GO

Set up timed execution steps

(1) Start SQL Server Management Studio and select Manage-maintenance plan option in the Object Explorer window.

(2) Right click on "Maintenance Plan", select "Maintenance Plan Wizard" in the Popup shortcut menu, the Maintenance Plan Wizard dialog box pops up, click "Next" button

(3) Popup "Select Target Server" dialog box, in the "Name" text box you can enter the name of the maintenance plan, in the "description" text box you can enter the description of the maintenance plan, "in the Server" text box you can enter the name of the server to use, and finally select the correct ID information, click the "Next" button.

(4) The Select Maintenance Task dialog box appears, in which you can choose to perform a SQL maintenance task, insert the Execute stored procedure statement

SQL code
    1. Use [DBNAME]
    2. GO
    3. EXEC [dbo]. [Usp_ims_defragment_indexes]

(5) Specify task execution plan

Related Article

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.