查找并删除重复索引?

时间:2011-11-28 11:44:31

标签: sql sql-server-2008 indexing

  

可能重复:
  Thoughts on index creation for SQL Server for missing indexes
  T-SQL for finding Redundant Indexes

我正在使用SQL Server 2008,并且拥有一个包含超过150个具有重复索引的表的数据库。

我发现了一些会列出重复索引的sql脚本,但我不确定是否应该信任它们。据说,他们说我有400多个重复索引;我不确定这是否正确,因此不想使用它们来自动删除欺骗。

如何明确定位重复索引并将其删除?

2 个答案:

答案 0 :(得分:4)

查看Tom LaRock出色的How to Find Duplicate Indexes博客文章 - 他详细解释了如何进行,并提供了检测重复索引的脚本。

答案 1 :(得分:0)

下面是代码段,它将显示重复索引,第二个查询将返回相同的脚本。你只需要提供表名。例如 设置@TableName ='SalaryMaster' 这可以通过在

上使用while循环来完成
select name from sys.tables

将它放入临时表应用while循环并执行以下代码

declare @TableName as varchar(50)

set @TableName = 'EmployeeMaster'
--- 1. 
select name as IndexName,Index_id as IndexID from sys.indexes 
where index_id  NOT in (
select MIN(index_id)  from (
select avg(column_id) avgCol,index_id  from sys.index_columns where
 object_id = object_id(@TableName)
group by index_id 
) as a group by avgCol  
) and object_id = object_id(@TableName)

--- 2.     
select '
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'''+@TableName+''') 
AND name = N'''+name+''')
DROP INDEX ['+name+'] ON '+@TableName+' WITH ( ONLINE = OFF )
' from sys.indexes 
where index_id  NOT in (
select MIN(index_id)  from (
select avg(column_id) avgCol,index_id  from sys.index_columns where
 object_id = object_id(@TableName)
group by index_id 
) as a group by avgCol  
) and object_id = object_id(@TableName)