根据sql server中的碎片重建索引

时间:2015-05-12 20:00:14

标签: sql-server stored-procedures sql-server-2012

所以,我正在网上寻找解决我问题的方法,我对DBA的事情相当新,所以请不要对我严厉:)

我有这段代码可以帮助我重建索引,如果它们被分割成一定的百分比。 它具有重组的IF条件,但我不需要它,我需要修改代码,以便查询某个数据库和模式的索引,并仅在碎片大于5%时重建。

USE [master]
GO

/****** Object:  StoredProcedure [dbo].[spKodyaz_Index_Maintenance]    Script Date: 19.11.2012 19:10:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[al]
(
    @DatabaseId smallint
)
AS

DECLARE
    @dbname sysname,
    @schema_name sysname,
    @object_id int,
    @object_name sysname,
    @index_name sysname,
    @avg_fragmentation float,
    @sql nvarchar(max)

CREATE TABLE ##tmpIndexMaintenance (
    object_schema_name sysname NULL,
    object_name sysname NULL,
    object_id int NULL,
    index_name sysname NULL,
    avg_fragmentation_in_percent float NULL
)

SET @dbname = DB_NAME(@DatabaseId);

SET @sql = N'USE [' + @dbname + '];
INSERT INTO ##tmpIndexMaintenance
SELECT
    object_schema_name(ps.object_id) as ObjectSchema,
    object_name(ps.object_id) as ObjectName,
    ps.object_id ObjectId,
    i.name as IndexName,
    ps.avg_fragmentation_in_percent
FROM [' + @dbname + '].sys.dm_db_index_physical_stats(' + CONVERT(nvarchar(5), @DatabaseId) + ', null, null, null, null) ps
inner join [' + @dbname + '].sys.indexes i
    on i.object_id = ps.object_id and i.index_id = ps.index_id
WHERE
    avg_fragmentation_in_percent > 5 -- reorganize and rebuild
    and ps.index_id > 0
ORDER BY avg_fragmentation_in_percent DESC'

--print @sql
EXEC (@sql);

DECLARE indexFragmentation CURSOR FAST_FORWARD FOR SELECT * FROM ##tmpIndexMaintenance

OPEN indexFragmentation
FETCH NEXT FROM indexFragmentation INTO @schema_name, @object_name, @object_id, @index_name, @avg_fragmentation

WHILE @@FETCH_STATUS = 0
BEGIN

    IF @avg_fragmentation > 30 -- ReBuild index
        SELECT @sql = 'USE [' + @dbname + ']; ALTER INDEX [' + @index_name +'] ON [' + @schema_name + '].[' + @object_name + '] REBUILD WITH (ONLINE = ON)';

    ELSE -- ReOrganize index
        SELECT @sql = 'USE [' + @dbname + ']; ALTER INDEX [' + @index_name +'] ON [' + @schema_name + '].[' + @object_name + '] REORGANIZE';

    PRINT @sql;
    EXEC (@sql);

    FETCH NEXT FROM indexFragmentation INTO @schema_name, @object_name, @object_id, @index_name, @avg_fragmentation

END

CLOSE indexFragmentation
DEALLOCATE indexFragmentation

DROP TABLE ##tmpIndexMaintenance


GO 

1 个答案:

答案 0 :(得分:1)

游标已经检索了碎片超过5%的数据库。只需删除if条件并默认重建它们

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql = 'USE [' + @dbname + ']; ALTER INDEX [' + @index_name +'] ON [' + @schema_name + '].[' + @object_name + '] REBUILD WITH (ONLINE = ON)';

    PRINT @sql;
    EXEC (@sql);

    FETCH NEXT FROM indexFragmentation INTO @schema_name, @object_name, @object_id, @index_name, @avg_fragmentation

END