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

前端 未结 7 1415
温柔的废话
温柔的废话 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 00:57

    From: Stephen Hill's Bloggie

    DECLARE @indexName VARCHAR(128)
    DECLARE @tableName VARCHAR(128)
    
    DECLARE [indexes] CURSOR FOR
    
            SELECT          [sysindexes].[name] AS [Index],
                            [sysobjects].[name] AS [Table]
    
            FROM            [sysindexes]
    
            INNER JOIN      [sysobjects]
            ON              [sysindexes].[id] = [sysobjects].[id]
    
            WHERE           [sysindexes].[name] IS NOT NULL 
            AND             [sysobjects].[type] = 'U'
            --AND               [sysindexes].[indid] > 1
    
    OPEN [indexes]
    
    FETCH NEXT FROM [indexes] INTO @indexName, @tableName
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
            --PRINT 'DROP INDEX [' + @indexName + '] ON [' + @tableName + ']'
            Exec ('DROP INDEX [' + @indexName + '] ON [' + @tableName + ']')
    
            FETCH NEXT FROM [indexes] INTO @indexName, @tableName
    END
    
    CLOSE           [indexes]
    DEALLOCATE      [indexes]
    
    GO
    

提交回复
热议问题