How can I drop all indexes in a SQL database with one command?

前端 未结 7 1567
温柔的废话
温柔的废话 2021-02-04 00:01

So, how can I drop all indexes in a SQL database with one command? I have this command that will get me all the 20 or so drop statements, but how can I run all of those drop s

7条回答
  •  名媛妹妹
    2021-02-04 00:48

    Minor improvements to the accepted answer that I had to make in my own case, mostly to account for schemas:

    declare @qry nvarchar(4000);
    select @qry = (select 'drop index ['+s.name+'].['+o.name+'].['+i.name+'];'
      from sys.indexes i join sys.objects o on i.object_id=o.object_id join sys.schemas s on o.schema_id=s.schema_id
      where o.type<>'S' and is_primary_key<>1 and index_id>0 and s.name<>'sys'
    for xml path(''));
    exec sp_executesql @qry
    

    Also: In my case it couldn't run in one go because the script becomes longer than 4000 characters. The only way I could think of to deal with that was to put a "top 20" on the inner select and execute it multiple times.

提交回复
热议问题