Disable all non-clustered indexes

后端 未结 5 1985
星月不相逢
星月不相逢 2020-12-29 05:36

I select a number of non-clustered indexes from my database with the following:

SELECT  sys.objects.name tableName,
        sys.indexes.name indexName
FROM           


        
5条回答
  •  被撕碎了的回忆
    2020-12-29 06:29

    Using a cursor to script things is more idiomatic than a temp table (and slightly briefer). To re-enable the indexes, replace DISABLE with REBUILD.

    DECLARE cur_indexes CURSOR FOR
    SELECT  sys.objects.name tableName,
            sys.indexes.name indexName
    FROM    sys.indexes
            JOIN sys.objects ON sys.indexes.object_id = sys.objects.object_id
    WHERE   sys.indexes.type_desc = 'NONCLUSTERED'
            AND sys.objects.type_desc = 'USER_TABLE'
    
    DECLARE @TblName NVARCHAR(255), @IdxName NVARCHAR(255)
    
    DECLARE @SQL NVARCHAR(MAX)
    
    open cur_indexes
    fetch next from cur_indexes into @TblName, @IdxName
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @SQL = N'ALTER INDEX ' + @IdxName + N' ON ' + @TblName + ' DISABLE;'
    
        EXEC sp_sqlexec @SQL    
    
        fetch next from cur_indexes into @TblName, @IdxName
    END
    
    close cur_indexes
    deallocate cur_indexes
    

提交回复
热议问题