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

前端 未结 7 1420
温柔的废话
温柔的废话 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:37

    this worked for me we skip sys indexes and for constraints

    declare @qry nvarchar(max);
    select @qry = (
    
        select  'IF EXISTS(SELECT * FROM sys.indexes WHERE name='''+ i.name +''' AND object_id = OBJECT_ID(''['+s.name+'].['+o.name+']''))      drop index ['+i.name+'] ON ['+s.name+'].['+o.name+'];  '
        from sys.indexes i 
            inner join sys.objects o on  i.object_id=o.object_id
            inner 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' and s.name!='sys' and is_unique_constraint=0
    for xml path(''));
    
    exec sp_executesql @qry
    

提交回复
热议问题