After spending some time to find out that there is no easy way to drop all indexes from a SQL table I came up with this script.
DECLARE @indexName NVARCHAR(128)DECLARE @dropIndexSql NVARCHAR(4000) DECLARE tableIndexes CURSOR FORSELECT name FROM sysindexesWHERE id = OBJECT_ID(N'tableName') AND indid > 0 AND indid < 255 AND INDEXPROPERTY(id, name, 'IsStatistics') = 0ORDER BY indid DESC OPEN tableIndexesFETCH NEXT FROM tableIndexes INTO @indexNameWHILE @@fetch_status = 0BEGIN SET @dropIndexSql = N'DROP INDEX tableName.' + @indexName EXEC sp_executesql @dropIndexSql FETCH NEXT FROM tableIndexes INTO @indexNameEND CLOSE tableIndexesDEALLOCATE tableIndexes
DECLARE @indexName NVARCHAR(128)DECLARE @dropIndexSql NVARCHAR(4000)
DECLARE tableIndexes CURSOR FORSELECT name FROM sysindexesWHERE id = OBJECT_ID(N'tableName') AND indid > 0 AND indid < 255 AND INDEXPROPERTY(id, name, 'IsStatistics') = 0ORDER BY indid DESC
OPEN tableIndexesFETCH NEXT FROM tableIndexes INTO @indexNameWHILE @@fetch_status = 0BEGIN SET @dropIndexSql = N'DROP INDEX tableName.' + @indexName EXEC sp_executesql @dropIndexSql
FETCH NEXT FROM tableIndexes INTO @indexNameEND
CLOSE tableIndexesDEALLOCATE tableIndexes
Use it at your own discretion. It should work fine on both SQL Server 2000 and SQL Server 2005.
Update on September 1st, 2006:
Thanks to Anthony Jones who pointed out that the script should drop the indexes in decscending order of indid. If the table has a clustered index it will be indid 1 which if dropped first will cause all other indexes to be rebuilt only to be subsequently dropped. I updated the script. Enjoy!