15

我有一个我想删除的非聚集索引(它是聚集索引的副本)。但是,它被外键约束使用。我希望能够确定哪个约束正在使用索引,所以我可以更新它以使用主键索引。

当我尝试放下它时:

DROP INDEX [idx_duplicate] ON [dbo].[MyTable]

我收到一个错误:

索引 'dbo.MyTable.idx_duplicate' 上不允许显式 DROP INDEX。它被用于 FOREIGN KEY 约束强制执行。

我试图通过以下查询找到罪魁祸首,但没有运气:

SELECT name
FROM sys.foreign_keys
WHERE OBJECT_NAME (referenced_object_id) = 'idx_duplicate'
4

3 回答 3

20

就像是

Select
    f.name,
    object_name(f.parent_object_id)
From
    sys.foreign_keys f
        inner join
    sys.indexes i
        on f.referenced_object_id = i.object_id and
           f.key_index_id = i.index_id
Where
    i.name = 'idx_duplicate' and
    i.object_id = object_id('[dbo].[MyTable]')
于 2013-09-09T21:37:38.750 回答
9

这将告诉您所涉及的表、外键和列:

select f.name
  , parentTable = o.name
  , parentColumn = c.name
  , foreignTable = ofr.name
  , foreignColumn = cfr.name
from sys.foreign_keys f
  inner join sys.foreign_key_columns fc on f.object_id = fc.constraint_object_id
  inner join sys.objects o on fc.parent_object_id = o.object_id
  inner join sys.columns c on fc.parent_column_id = c.column_id
    and o.object_id = c.object_id
  inner join sys.objects ofr on fc.referenced_object_id = ofr.object_id
  inner join sys.columns cfr on fc.referenced_column_id = cfr.column_id
    and ofr.object_id = cfr.object_id
  inner join sys.indexes i on ofr.object_id = i.object_id
where i.name = 'MyIndex'

SQL Fiddle 与演示

于 2013-09-09T21:39:51.480 回答
3

我意识到这篇文章已经有几年的历史了,但如果不深入挖掘它,我不会放弃任何这样的索引。即使键列相同,非聚集索引也与聚集索引不同。NCI 的叶级比 CI 的叶级窄得多,因此每页包含的信息行数比 CI 多得多。通过删除 NCI,您实际上可能会导致性能问题(尤其是对于另一个表上的插入)。

于 2015-10-09T18:57:39.377 回答