我想知道列出数据库中所有表的所有索引的最简单方法是什么。
我应该为每个表调用 sp_helpindex
并将结果存储在临时表中,还是有更简单的方法?
任何人都可以解释为什么约束存储在 sysobjects 中而索引不是?
最佳答案
以下是您需要的查询类型的示例:
select
i.name as IndexName,
o.name as TableName,
ic.key_ordinal as ColumnOrder,
ic.is_included_column as IsIncluded,
co.[name] as ColumnName
from sys.indexes i
join sys.objects o on i.object_id = o.object_id
join sys.index_columns ic on ic.object_id = i.object_id
and ic.index_id = i.index_id
join sys.columns co on co.object_id = i.object_id
and co.column_id = ic.column_id
where i.[type] = 2
and i.is_unique = 0
and i.is_primary_key = 0
and o.[type] = 'U'
--and ic.is_included_column = 0
order by o.[name], i.[name], ic.is_included_column, ic.key_ordinal
;
这个在某种程度上特定于某种目的(我在一个小型 C# 应用程序中使用它来查找重复索引并格式化输出,以便人类实际上可以读取)。但您可以轻松地根据您的需求进行调整。
关于sql-server - 列出所有索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/425475/