重建索引过程但失败

时间:2013-12-02 12:49:11

标签: sql sql-server

检查以下程序 我试图执行上面的程序运行但索引不重建或REORGANIZE请在这里建议

SELECT  
    dbtables.[name] as 'Table_Name',
    dbindexes.[name] as 'Index_Name',
    indexstats.avg_fragmentation_in_percent AS 'frag_count'
into #tmp
FROM
    sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
    INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
    INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
    INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id] AND indexstats.index_id = dbindexes.index_id
WHERE
    indexstats.database_id = DB_ID()
    and indexstats.avg_fragmentation_in_percent > 5
    and dbindexes.[name] is not NULL

ALTER TABLE #tmp ADD SQLCommand varchar(1000);
Update #tmp 
set SQLCommand=  'ALTER INDEX '+ Index_Name + ' ON ' + Table_Name + ' REBUILD '-- WITH (ONLINE=ON)' 
where frag_count >30;

Update #tmp 
set SQLCommand=  'ALTER INDEX '+ Index_Name + ' ON ' + Table_Name + ' REORGANIZE' --WITH (ONLINE=ON)' 
where frag_count < 30;

select @count= COUNT(1) from #tmp

WHILE (@intFlag <=@count)
BEGIN
    PRINT @intFlag
    select  @sql =  SQLCommand from  #tmp --where ID= @intFlag;

    PRINT @sql
    execute ( @sql)
    SET @intFlag = @intFlag + 1
    CONTINUE;
END

0 个答案:

没有答案