Technical Article

disable/enable indexes for table

,

I developed this script in order to speedup datacopy operations. You can use this script to disable indexes or enabling them (by rebuilding the index).

This script only disables indexes which are added for performance considerations. Clustered indexes and key/constraint indexes are not touched. Execute this script in your actual database (no hardcoded database references).

Params:

  • @objectname : Tablename
  • @switch : determines disabling or enabling indexes 0 = disable, 1= enable
  • @debug: when 1, only output is showed. no actual execution
  • @verbose: when 1, additional information is showed

Warning: since there's no check on tabletype, you could alter system indexes.

if object_id('usp_toggle_index') is not null
    drop procedure usp_toggle_index
go

create procedure usp_toggle_index(@objectname sysname, @switch bit = 0, @debug bit = 0, @verbose bit = 1) as
begin
    declare @SQLCmd nvarchar(512)
    declare @action nvarchar(16)
    declare @counter int

    set @counter = 0

    if @switch = 0
        set @action = ' disable;'
    else
        set @action = ' rebuild;'
        
    declare c_toggle_index cursor for
        select    'alter index ' + QUOTENAME(name) + ' on ' + QUOTENAME(@objectname) + @action
        from    sys.indexes
        where    type_desc = 'nonclustered'
        and        is_unique = 0
        and        is_primary_key = 0
        and        is_unique_constraint = 0
        and        is_disabled = @switch
        and        object_id = object_id(@objectname)

    open    c_toggle_index
    
    fetch    next
    from    c_toggle_index 
    into    @SQLCmd

    while @@fetch_status = 0
        begin
            set @counter = @counter + 1
            if @debug = 0
                exec (@SQLCmd)
            else
                print @SQLCmd

            fetch next
            from c_toggle_index 
            into @SQLCmd
        end

    close c_toggle_index
    deallocate c_toggle_index

    if @verbose = 1
        print '- processed ' + cast(@Counter as varchar) + ' indexes for table ' + @objectname
end
go

Rate

4.5 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

4.5 (2)

You rated this post out of 5. Change rating