我想知道是否有办法根据列名验证特定表的SQL Server数据库中是否存在索引:
假设我运行以下脚本:
CREATE NONCLUSTERED INDEX [MyIndexName]
ON [dbo].[MyTable] ([CustomerId])
INCLUDE ([Id],[ModificationDate],[ProductId])
GO
现在我想根据表名和列(以及include子句中的列)检查索引是否存在,而不是实际索引名。
(SQL Server 2008 R2)
由于
答案 0 :(得分:34)
尝试此查询:
if exists(
SELECT 1
FROM sys.indexes
WHERE name = 'INDEX'
AND object_id = OBJECT_ID('TABLENAME')
)
begin
....
end
答案 1 :(得分:0)
信息在目录元数据视图中可用,类似于:
select ...
from sys.indexes i
join sys.index_columns ic on i.object_id = ic.object_id
and i.index_id = ic.index_id
join sys.columns c
on ic.object_id = c.object_id
and ic.index_column_id = c.column_id
where i.object_id = object_id('MyTable')
and (c.name = 'CustomerId' and ic.key_ordinal = 1 and ic.is_descending_key = 0)
or (ic.is_included_column = 1 and c.name in ('Id', 'ModificationDate', 'ProductId'));
这不是产生是/否答案,而是向您显示可能已经涵盖您正在计划的索引的索引。您需要考虑关键位置,关键方向和包含的列,覆盖重叠((K1,K2)覆盖(K1)上的索引,以及包括(C1,C2,C3)覆盖(C1,C3)的索引对于真正的生产系统,您需要考虑隐式包含的列(例如聚簇索引键),索引过滤器表达式和索引数据空间的差异(即分区)(
)。