Wednesday, November 17, 2010

List tables, index and keys

Here's a code that list the columns used in each index for each table.

with table_indexes
as
(
   select 
   row_num = row_number() over(partition by t.name, i.name order by t.name, i.name, ci.key_ordinal),
   t.name as table_name, i.name as table_index, c.name as index_keys
   from sys.tables t
      left join sys.indexes i on t.object_id = i.object_id and i.index_id > 0
      left join sys.index_columns ci on i.object_id = ci.object_id and i.index_id = ci.index_id
      left join sys.columns c on c.object_id = ci.object_id and c.column_id = ci.column_id
)  
select 
   table_name = case when row_num = 1 then table_name else '' end,
   table_index = case when row_num = 1 then table_index else '' end,
   index_keys
from table_indexes
As always, comments, suggestions, objections :) are all welcome...


~~ CK

No comments:

Post a Comment