【SQL Server】获取指定表上的索引信息(SQL版)

对于如何获取索引信息,想必大家对sp_helpindex并不陌生,这也是常用方法,但是它并不能提供包含列以及filter信息,于是乎尝试着写了如下SQL code,当然和大神们写的查询的sp不能相提并论,但是凑合着使用应该没有问题。

SELECT index_name,
       index_description,
       (LEFT(ind_col, LEN(ind_col)-1)
       + case when include_col IS NOT NULL
           THEN ' INCLUDE (' + LEFT(include_col, LEN(include_col)-1) + ')'
         else '' end) AS index_keys
FROM
(SELECT i.name AS index_name, 
        (SELECT CONVERT(varchar(max), 
         case when i.index_id = 1 then 'clustered' else 'nonclustered' end  
         + case when i.ignore_dup_key <>0 then ', ignore duplicate keys' else '' end  
         + case when i.is_unique <>0 then ', unique' else '' end  
         + case when i.is_hypothetical <>0 then ', hypothetical' else '' end  
         + case when i.is_primary_key <>0 then ', primary key' else '' end  
         + case when i.is_unique_constraint <>0 then ', unique key' else '' end
         + case when s.auto_created <>0 then ', auto create' else '' end  
         + case when s.no_recompute <>0 then ', stats no recompute' else '' end  
         + ' located on ' + ISNULL(name, '')
         + case when i.has_filter = 1 then ', filter={' + i.filter_definition + '}' else '' end)
	 FROM sys.data_spaces
	 WHERE data_space_id = i.data_space_id ) AS 'index_description',
	 (SELECT INDEX_COL(OBJECT_NAME(i.object_id), i.index_id, key_ordinal),
	         CASE WHEN is_descending_key = 1 THEN N'(-)' ELSE N'' END + ','
	  FROM sys.index_columns
	  WHERE object_id = i.object_id 
		AND index_id = i.index_id 
		AND key_ordinal <> 0
	  ORDER BY key_ordinal FOR XML PATH('')) AS ind_col,
         (SELECT col.name + ','
          FROM sys.index_columns inxc 
          JOIN sys.columns col
            ON col.object_id = inxc.object_id
               AND col.column_id = inxc.column_id
          WHERE inxc.object_id = i.object_id 
                AND inxc.index_id = i.index_id
                AND inxc.is_included_column = 1
          FOR XML PATH('')) AS include_col
FROM sys.indexes i
JOIN sys.stats s
ON i.object_id = s.object_id
  AND i.index_id = s.stats_id  
WHERE i.object_id = object_id('Table_Name')) Ind
ORDER BY index_name


你可能感兴趣的:(SQL,Server)