在一個大型數(shù)據(jù)庫中,數(shù)據(jù)的更改是非常頻繁的。
而建立在這些數(shù)據(jù)上的索引也是需要經(jīng)常去維護的。
否則這這些數(shù)據(jù)索引就起不到起應(yīng)起的作用。甚至?xí)蔀閿?shù)據(jù)庫本身的負(fù)擔(dān)。
我們就要定期的對數(shù)據(jù)庫的索引進行維護 我在MSDN上發(fā)現(xiàn)了這個腳本不過其中有些小問題我已經(jīng)修正 大家可以使用這個腳本對數(shù)據(jù)庫的索引進行日常維護
復(fù)制代碼 代碼如下:
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);
DECLARE @dbId int;
-- 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.
set @dbId=DB_ID();
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 (@dbId, 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.
OPEN partitions;
-- Loop through the partitions.
FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag;
WHILE @@FETCH_STATUS = 0
BEGIN;
SELECT @objectname = o.name, @schemaname = s.name
FROM sys.objects AS o
JOIN sys.schemas as s ON s.schema_id = o.schema_id
WHERE o.object_id = @objectid;
SELECT @indexname = name
FROM sys.indexes
WHERE object_id = @objectid AND index_id = @indexid;
SELECT @partitioncount = count (*)
FROM sys.partitions
WHERE object_id = @objectid AND index_id = @indexid;
-- 30 is an arbitrary decision point at which to switch between reorganizing and rebuilding
IF @frag 30.0
BEGIN;
SELECT @command = 'ALTER INDEX [' + @indexname + '] ON ' + @schemaname + '.[' + @objectname + '] REORGANIZE';
IF @partitioncount > 1
SELECT @command = @command + ' PARTITION=' + CONVERT (CHAR, @partitionnum);
EXEC (@command);
END;
IF @frag >= 30.0
BEGIN;
SELECT @command = 'ALTER INDEX [' + @indexname +'] ON ' + @schemaname + '.[' + @objectname + '] REBUILD';
IF @partitioncount > 1
SELECT @command = @command + ' PARTITION=' + CONVERT (CHAR, @partitionnum);
EXEC (@command);
END;
PRINT 'Executed ' + @command;
FETCH NEXT FROM partitions INTO @objectid, @indexid, @partitionnum, @frag;
END;
-- Close and deallocate the cursor.
CLOSE partitions;
DEALLOCATE partitions;
-- drop the temporary table
IF EXISTS (SELECT name FROM sys.objects WHERE name = 'work_to_do')
DROP TABLE work_to_do;
GO
這個腳本在運行時 會建立一個表 work_to_do 整理完畢后會自動刪除這個表。如果大家不喜歡這樣的話也可以用 一個 臨時表解決 .
您可能感興趣的文章:- 通過T_sql語句向其中一次填入一條數(shù)據(jù)或一次填入多條數(shù)據(jù)的方式填充數(shù)據(jù)
- sql語句查詢數(shù)據(jù)庫中的表名/列名/主鍵/自動增長值實例
- Mysql 自動增加設(shè)定基值的語句
- SQL語句實現(xiàn)查詢并自動創(chuàng)建Missing Index
- SQL語句中公共字段的自動填充方法