rahul ahuja

rahul ahuja

  • NA
  • 80
  • 34.2k

Get SQL Table Indexes script by its name

Jul 31 2015 9:54 AM
Hi Guys,
 
I need help to get the actual script of the index using some sql command or sql query. As we know sp_helptext 'Proc_Name' .  
will give us procedure acutal code. i need to do with index. but not sure how to do that. Where actually indexes are stored so i can do query on the table and get its script by sql query. Or if any one know the way how to retrive it.
 
Here is query which gives me the all Table Name, Index Name, Index Id Column Name, Column Id
 
SELECT
t.name as TableName,
ind.name as IndexName,
ind.index_id as IndexId,
ic.index_column_id as ColumnsID,
col.name as ColumnName
From
sys.indexes ind
INNER JOIN
sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id= ic.index_id
INNER JOIN
sys.columns col on ic.object_id = col.object_id and ic.column_id= col.column_id
inner join sys.tables t on ind.object_id = t.object_id
WHERE
ind.is_primary_key=0
and ind.is_unique=0
and ind.is_unique_constraint=0
and t.is_ms_shipped=0
ORDER BY
t.name, ind.name, ind.index_id, ic.index_column_id.
 
I know the following way were we get index can be scripted 
Under Object Explorer -> Databases -> Database -> Tables - > Indexes -> right-click on index - > Create Script as ..
but i want to do it with query  which is fired by my console application
 
 
 
Thanks
 
 
 
 

Answers (3)