2015-08-05 4 views
0

Как получить все столбцы индекса, включая отфильтрованные столбцы?Список всех столбцов индекса (включая отфильтрованные) в SQL Server

if object_id('dbo.tTestIndex') is not null 
    drop table dbo.tTestIndex; 

create table dbo.tTestIndex (a int, b int, c int); 

create index X_tTestIndex on dbo.tTestIndex (a) include (b) where c > 0; 

select i.name, i.filter_definition, c.name, ic.is_included_column 
from sys.indexes i 
inner join sys.index_columns ic on i.object_id = ic.object_id and i.index_id = ic.index_id 
left join sys.columns c on ic.object_id = c.object_id and ic.column_id = c.column_id 
where i.object_id = object_id('dbo.tTestIndex'); 

if object_id('dbo.tTestIndex') is not null 
    drop table dbo.tTestIndex; 

В этом примере приведены две строки вместо трех.

index_name | filter_definition | column_name | is_included_column 
-------------+-------------------+-------------+------------------- 
X_tTestIndex | ([c]>(0))   | a   | 0 
X_tTestIndex | ([c]>(0))   | b   | 1 
+0

Я не думаю, что есть простой способ получить эту информацию. Он возвращается в 'filter_defintion' в' sys.indexes', но вам придется вручную дразнить выражение отдельно, чтобы получить имена столбцов. –

+0

Может быть. Но когда я пытаюсь выполнить эту «alter table dbo.tTestIndex alter column c bigint», я получаю сообщение об ошибке «Индекс« X_tTestIndex »зависит от столбца« c ». Я не думаю, что SQL Server анализирует столбец' filter_definition' , – GriGrim

ответ

2

Вы можете использовать представление каталога sys.sql_expression_dependencies, чтобы узнать столбцы, на которых опирается ваш фильтр:

SELECT i.name, i.filter_definition, c.name, is_included_column = 0 
FROM sys.indexes AS i 
     INNER JOIN sys.sql_expression_dependencies AS d 
      ON d.referencing_id = i.[object_id] 
      AND d.referencing_minor_id = i.index_id 
      AND d.referencing_class_desc = 'INDEX' 
     INNER JOIN sys.columns AS c 
      ON c.[object_id] = d.referenced_id 
      AND c.column_id = d.referenced_minor_id 
WHERE i.[object_id] = OBJECT_ID(N'dbo.tTestIndex'); 

Вы можете просто UNION это ваш первоначальный запрос, чтобы получить все столбцы.

Смежные вопросы