【问题标题】:Finding and removing duplicate indexes? [duplicate]查找和删除重复索引? [复制]
【发布时间】:2011-11-28 11:44:31
【问题描述】:

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

我使用的是 SQL Server 2008,并且有一个包含 150 多个具有重复索引的表的数据库。

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

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

【问题讨论】:

  • 在准备迁移时进行了清理,但您已经有了两个不错的答案。你能试试吗?如果你有一个可以接受的答案,我宁愿不迁移。
  • @Will:非常感谢我已经尝试过这两种方法。但我仍在等待完美的答案。谢谢。

标签: sql sql-server-2008 indexing


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    下面是显示重复索引的代码段,第二个查询将返回相同的脚本。您只需要提供表名。例如 设置@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)
    

    【讨论】:

    • 谢谢,但它不能正常工作。我试过了,它忽略了一些重复的索引。
    • Yakub,你能详细说明一下重复索引吗?上面的查询将为 u 提供具有相同列名的索引。就是这样 。你想要这样还是不同。
    • 我在同一列column1 + column2上有两个索引,两个索引中包含的列不同,所以我想它应该列在重复列表中。
    • yakub sys.indexes 是一个系统视图,它列出数据库中的所有索引 sys.index_columns 列出所有列名的索引
    猜你喜欢
    • 1970-01-01
    • 2012-01-16
    • 2012-09-11
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多