SQL Server索引维护指导
本文以笔者在实际工作中对SQL Server数据库中索引维护的思路和方法为导向,为大家介绍SQL Server索引维护相关的知识和方法。
针对SQL Server 2005的通用维护过程
(碎片小于30%的联机组织,碎片>=30%的脱机重建):
| -- ensure a USE <databasename> statement has been executed first. SET NOCOUNT ON; DECLARE @objectid int; DECLARE @indexid int; DECLARE @partitioncount bigint; DECLARE @schemaname sysname; DECLARE @objectname sysname; DECLARE @indexname sysname; DECLARE @partitionnum bigint; DECLARE @partitions bigint; DECLARE @frag float; DECLARE @command varchar(8000); -- ensure the temporary table does not exist IF EXISTS (SELECT name FROM sys.objects WHERE name = 'work_to_do') DROP TABLE work_to_do; -- conditionally select from the function, converting object and index IDs to names. SELECT object_id AS objectid, index_id AS indexid, partition_number AS partitionnum, avg_fragmentation_in_percent AS frag INTO work_to_do FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') WHERE avg_fragmentation_in_percent > 10.0 AND index_id > 0; -- Declare the cursor for the list of partitions to be processed. DECLARE partitions CURSOR FOR SELECT * FROM work_to_do; -- Open the cursor. -- Loop through the partitions. WHILE @@FETCH_STATUS = 0 SELECT @indexname = name SELECT @partitioncount = count (*) -- 30 is an arbitrary decision point at which to switch between reorganizing and rebuilding IF @frag >= 30.0 FETCH NEXT FROM partitions INTO @objectid, @indexid, @partitionnum, @frag; -- drop the temporary table |
总结
索引的维护是有参考依据的,应该根据具体的碎片情况以及是否需要联机操作等需求,采用合理的维护方法。自动化的索引维护策略是可行的。
IT专家网原创文章,未经许可,严禁转载!
- 本文关键词:

