I have a index defined on a one single column of a table. I am using the following query to determine whether the index exist on one column or not. This seems to work but is there a better way to do this? I looked at other solutions on stackoverflow but that does not seem to work well.
SELECT MIN(ColumnsCount) FROM
(
SELECT COUNT(*) AS ColumnsCount,
SysIndex.name
FROM sys.indexes As SysIndex
Inner Join sys.index_columns As SysIndexCol On SysIndex.object_id = SysIndexCol.object_id And SysIndex.index_id = SysIndexCol.index_id
Inner Join sys.columns As SysCols On SysIndexCol.column_id = SysCols.column_id And SysIndexCol.object_id = SysCols.object_id
WHERE SysIndex.name
in
(
Select
SysIndex.name
From
sys.indexes As SysIndex
Inner Join sys.index_columns As SysIndexCol On SysIndex.object_id = SysIndexCol.object_id And SysIndex.index_id = SysIndexCol.index_id
Inner Join sys.columns As SysCols On SysIndexCol.column_id = SysCols.column_id And SysIndexCol.object_id = SysCols.object_id
Where
type <> 0
And SysIndex.object_id in (Select systbl.object_id from sys.tables as systbl Where SysTbl.name = 'TableName')
And SysCols.name = 'ColName'
)
GROUP BY SysIndex.name) A
4条答案
按热度按时间eyh26e7m1#
What you are retrieving is the lowest number of columns used in an index on a given table, where the index includes a given column. Your query can be simplified to:
I've added the condition in
ic.is_included_column = 0
, on the assumption that you don't want to include non key columns in the account, nor are you interested in indexes where the given column is not a key column. If this assumption is incorrect then remove this predicate.However, if your current query works, I don't see that there is much benefit from optimising a query on the system catalogs. They aren't likely to be performance killers.
ljo96ir52#
Not sure why such a big query but if I have understood correctly, you are trying to find whether a specific index
idx
is present in tableX
. if that's the case then you can directly querysys.indexes
table like below (assuming your index nameidx123
and your table name istable1
)nuypyhwy3#
What about this it's simple and you don't need to be root user
ffx8fchx4#
This worked for me: