views:

349

answers:

2

I am about to write a script to add new indexes to a database, I wish that script to work regardless of the current indexes the database has.

Therefore the first step in the script should be to remove all the current indexes. (I could just as easily run .net code, but I think TSQL will be less painful for this type of thing)

(This is for use in development for small databases, so I don’t mind if it is not the quickest way of managing indexes, this needs to work for SqlServer 2005 and SqlServer 2008)

+1  A: 

I found this at http://refactormycode.com/codes/522-drop-all-indexes-in-sql-server. It appears to drop all indexes in the current database:

Declare @Index varchar(128)
Declare @Table varchar(128)

Select
SysIndexes.Name As 'Index',
SysObjects.Name As 'Table'
Into
#Indexes
From
SysIndexes
Inner Join SysObjects On
    SysObjects.id = SysIndexes.id
Where
SysIndexes.Name Is Not Null
and SysObjects.XType = 'U'
Order By
SysIndexes.Name,
SysObjects.Name

While (Select Count(*) From #Indexes) > 0
Begin
    Set @Index = (Select Top 1 [Index] From #Indexes)
    Set @Table = (Select Top 1 [Table] From #Indexes)

    --Print 'Drop Index [' + @Index + '] On [' + @Table + ']' + Char(13)
    Exec ('Drop Index [' + @Index + '] On [' + @Table + ']')
    Delete From #Indexes Where [Index] = @Index and [Table] = @Table
End

Drop Table #Indexes
Dolbz
thanks, it give meAn explicit DROP INDEX is not allowed on index 'Application.PK_dbo.Application'. It is being used for PRIMARY KEY constraint enforcement.(Maybe what I am asking for is not possible)
Ian Ringrose
I think you would have to drop the primary key constraint to drop PK indexes. You can use something like... 'ALTER TABLE TableNameDROP CONSTRAINT pk_Name'. Remember this will affect referential integrity.
Dolbz