2011-11-28 114 views
3

可能重复:
Thoughts on index creation for SQL Server for missing indexes
T-SQL for finding Redundant Indexes查找并删除重复的索引?

我使用SQL Server 2008和有一个包含了重复的索引超过150个表的数据库。

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

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

+0

整理了在制备用于迁移,但你已经有两个体面的答案。你可以试试吗?如果您有可接受的答案,我宁愿不迁移。 – Will

+0

@威尔:非常感谢我已经尝试了他们两个。但我仍在等待完美的答案。谢谢。 –

回答

4

查看Tom LaRock的优秀How to Find Duplicate Indexes博客文章 - 他详细解释了如何处理,还提供了检测重复索引的脚本。

0

下面是代码段,它将显示重复索引,第二个查询将返回相同的脚本。你只需要提供表名。对于实施例 组@tablename =“SalaryMaster” 这可以通过使用完成while循环上

select name from sys.tables 

放入临时表应用而循环,并执行下面的代码

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'''[email protected]+''') 
AND name = N'''+name+''') 
DROP INDEX ['+name+'] ON '[email protected]+' 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) 
+0

谢谢,但它工作不正常。我试过了,它忽略了一些重复的索引。 –

+0

Yakub,请你详细说明重复索引。上面的查询将为您提供具有相同列名称的索引。而已 。你是否想要这样或不同。 – sameer

+0

我有两个索引都在同一列column1 + column2,包含在两个索引中的列是不同的,所以我想它应该列在重复列表中。 –