我即将编写一个脚本来向数据库添加新索引,我希望无论数据库当前的索引如何,该脚本都能正常工作。
因此,脚本的第一步应该是删除所有当前索引。 (我可以很容易地运行.net代码,但我认为TSQL对这类事情的痛苦会少一些)
(这是用于小型数据库的开发,所以我不介意它是否是管理索引的最快方法,这需要适用于SqlServer 2005和SqlServer 2008)
答案 0 :(得分:6)
我在http://refactormycode.com/codes/522-drop-all-indexes-in-sql-server找到了这个。它似乎删除了当前数据库中的所有索引:
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
答案 1 :(得分:1)
另一个工作脚本:
http://blogs.msdn.com/b/tihot/archive/2006/01/16/513548.aspx
DECLARE @indexName NVARCHAR(128)
DECLARE @dropIndexSql NVARCHAR(4000)
DECLARE tableIndexes CURSOR FOR
SELECT name FROM sysindexes
WHERE id = OBJECT_ID(N'tableName') AND
indid > 0 AND indid < 255 AND
INDEXPROPERTY(id, name, 'IsStatistics') = 0
ORDER BY indid DESC
OPEN tableIndexes
FETCH NEXT FROM tableIndexes INTO @indexName
WHILE @@fetch_status = 0
BEGIN
SET @dropIndexSql = N'DROP INDEX tableName.' + @indexName
EXEC sp_executesql @dropIndexSql
FETCH NEXT FROM tableIndexes INTO @indexName
END
CLOSE tableIndexes
DEALLOCATE tableIndexes