Home  >  Article  >  Database  >  解决SQL Server 表或索引的碎片问题

解决SQL Server 表或索引的碎片问题

WBOY
WBOYOriginal
2016-06-07 16:21:331243browse

对表进行长期的修改或删除会产生大量的碎片,影响数据库性能。解决办法就是把表或索引重建,消除碎片,达到优化的目的。 直接上代码: /*查询碎片,avg_fragmentation_in_percent就是索引占的百分比,大于30都是不正常的,需要重建*/ DECLARE @db_id int; DE

   对表进行长期的修改或删除会产生大量的碎片,影响数据库性能。解决办法就是把表或索引重建,消除碎片,达到优化的目的。

  直接上代码:

  /*查询碎片,avg_fragmentation_in_percent就是索引占的百分比,大于30都是不正常的,,需要重建*/

  DECLARE @db_id int;

  DECLARE @object_id int;

  SET @db_id = DB_ID(N'AdventureWorks2008R2');

  SET @object_id = OBJECT_ID(N'AdventureWorks2008R2.Person.Address');

  IF @db_id IS NULL

  BEGIN;

  PRINT N'Invalid database';

  END;

  ELSE IF @object_id IS NULL

  BEGIN;

  PRINT N'Invalid object';

  END;

  ELSE

  BEGIN;

  SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);

  END;

  GO

  /*重建表*/

  alter table rebuild

  /*重建索引*/

  alter index ON rebuild

Statement:
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