Home Database Mysql Tutorial SQL Server 重建索引 Rebuild Index

SQL Server 重建索引 Rebuild Index

Jun 07, 2016 pm 02:56 PM
index server sql index reconstruction

重建索引是为了减少数据碎片。数据碎片会导致 SQL Server 进行不必要的数据读,降低 SQL Server 的性能。重建索引也会同时更新列统计,而如果查询所使用的列缺少或遗漏统计信息,这可能导致 SQL Server 内部的优化器选择比预期效率低的查询计划。 如果您重建

重建索引是为了减少数据碎片。数据碎片会导致SQL Server进行不必要的数据读,降低SQL Server的性能。重建索引也会同时更新列统计,而如果查询所使用的列缺少或遗漏统计信息,这可能导致SQL Server内部的优化器选择比预期效率低的查询计划。

 

如果您重建了某张表上的聚集索引,该表上的非聚集索引也同时会被更新。

 

 

要更新索引,您可以使用Maintenance Wizard(相关内容您可以参考http://msdn.microsoft.com/en-us/library/ms180074.aspx),或在SQL Server代理(Agent)中运行如下的自定义代码来更新某个数据库中所有表上的索引:

您可以根据您的需求修改DBREINDEX的参数。

需要注意的是,重建非聚集索引时该表会暂时加上共享锁,对用户不可进行SELECT以外的操作;重建聚集索引时该表会暂时加上排外锁,不允许任何用户访问。因此需要制定好计划来预防可能的访问问题。

 

REBUILD有一个fill factor参数,如果fill factor设置为100%,这意味着每一个索引页都是完全满的,如果fill factor设置为50%意味着每个索引页都是半满的。对于fill factor 100%,每次新插入或更新一个记录,由于当前页没有空间可用,可能有分页情况产生。过多的分页会降低SQL Server的性能。下面具体举个例子:

假设您在一张表上建立了一个使用默认fill factor的新索引。当SQL Server创建索引时,它会把索引放置在连续的物理页上,以使数据顺序地被读,I/O访问最优化。但当表因INSERTUPDATEDELETE等操作增长改变时,分页发生,SQL Server在磁盘的其他地方分配新的页,导致新的页与原物理页不连续,增加了随机I/O,访问索引页变慢。

 

那么fill factor的合适值应该为多少?这取决于表的读/写比:

低更新表(读/写比:1001):100% fill factor

高更新表(写超过读):50%-70% fill factor

居中:80%-90% fill factor

 

过低的fill factor会增加页的数量,也会导致更多的页需要被移至缓存,缓存中有用的数据减少。默认的fill factor0(即100% fill factor),通常这不是个好的选择,特别是对于聚集索引。

如果您无法判断设置什么fill factor,您首先需要确定磁盘的读/写比.方法就是使用如下两个计数器:

Physical Disk Object: % Disk Read Time Physical Disk Object: % Write Time。另外一个可能有用的计数器就是:SQL Server Access Methods: Pages Splits/Sec。这个计数器测量SQL Server内每秒分页的次数。如果该数值过高,您需要降低fill factor防止新的分页。

 

如果您想确认您的索引因分页产生的碎片程度,您可以运行DBCC SHOWCONTIG命令。如果看特定表和特定索引,您可以运行如下代码:

结果集中最重要的参数是Scan Density,越接近100%越好。如果Scan Density小于75%,那么您可能需要重建表中的索引。

对于小于100数据页,重建索引并不会有明显的性能改善。这是因为物理硬件缓存,SQL Server缓存和SQL Server预读机制隐藏了碎片的负面作用。但对于非常大的表,重建索引会使它受益匪浅,因为涉及大量磁盘I/O操作。

ALTER INDEX Idx_name ON tblCompany REBUILD
Copy after login
 USE databasename --Enter the name of the database you want to reindex
DECLARE @TableName VARCHAR(255)
DECLARE tablecursor CURSOR FOR
  SELECT table_name
  FROM   information_schema.tables
  WHERE  table_type = 'base table'

OPEN tablecursor

FETCH next FROM tablecursor INTO @TableName

WHILE @@FETCH_STATUS = 0
  BEGIN
      DBCC dbreindex(@TableName, '', 90)

      FETCH next FROM tablecursor INTO @TableName
  END

CLOSE tablecursor

DEALLOCATE tablecursor  
Copy after login
 --Script to identify table fragmentation
--Declare variables
DECLARE @ID        INT,
        @IndexID   INT,
        @IndexName VARCHAR(128)

--Set the table and index to be examined
SELECT @IndexName = 'index_name' --enter name of index
SET @ID = Object_id('table_name') --enter name of table
--Get the Index Values
SELECT @IndexID = indid
FROM   sysindexes
WHERE  id = @ID
       AND name = @IndexName

--Display the fragmentation
DBCC showcontig (@id, @IndexID)  
Copy after login
--方法一:

 USE adventureworks

go

EXEC Sp_msforeachtable
  @command1="print '?' DBCC DBREINDEX ('?', '', 90)"

go

EXEC Sp_updatestats

go  

--方法二:

USE adventureworks

go

CREATE PROCEDURE Usp_reindex_updatestats
AS
    DECLARE @MyTable VARCHAR(255)
    DECLARE mycursor CURSOR FOR
      SELECT table_name
      FROM   information_schema.tables
      WHERE  table_type = 'base table'
             AND table_name NOT LIKE 'sys%'

    OPEN mycursor

    FETCH next FROM mycursor INTO @MyTable

    WHILE @@FETCH_STATUS = 0
      BEGIN
          PRINT 'Reindexing Table:  ' + @MyTable

          DBCC dbreindex(@MyTable, '', 90)

          FETCH next FROM mycursor INTO @MyTable
      END

    CLOSE mycursor

    DEALLOCATE mycursor

    EXEC Sp_updatestats

go  
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What file is index.html? What file is index.html? Feb 19, 2024 pm 01:36 PM

index.html represents the home page file of the web page and is the default page of the website. When a user visits a website, the index.html page is usually loaded first. HTML (HypertextMarkupLanguage) is a markup language used to create web pages, and index.html is also an HTML file. It contains the structure and content of a web page, as well as tags and elements used for formatting and layout. Here is an example index.html code: &lt

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

What does the identity attribute in SQL mean? What does the identity attribute in SQL mean? Feb 19, 2024 am 11:24 AM

What is Identity in SQL? Specific code examples are needed. In SQL, Identity is a special data type used to generate auto-incrementing numbers. It is often used to uniquely identify each row of data in a table. The Identity column is often used in conjunction with the primary key column to ensure that each record has a unique identifier. This article will detail how to use Identity and some practical code examples. The basic way to use Identity is to use Identit when creating a table.

How to install, uninstall, and reset Windows server backup How to install, uninstall, and reset Windows server backup Mar 06, 2024 am 10:37 AM

WindowsServerBackup is a function that comes with the WindowsServer operating system, designed to help users protect important data and system configurations, and provide complete backup and recovery solutions for small, medium and enterprise-level enterprises. Only users running Server2022 and higher can use this feature. In this article, we will explain how to install, uninstall or reset WindowsServerBackup. How to Reset Windows Server Backup If you are experiencing problems with your server backup, the backup is taking too long, or you are unable to access stored files, then you may consider resetting your Windows Server backup settings. To reset Windows

How to solve the 5120 error in SQL How to solve the 5120 error in SQL Mar 06, 2024 pm 04:33 PM

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

See all articles