This is a really complicated thing to do in SQL code. It's complicated because indexes have so many options. Potential issues/complications:
- Covering indexes
- Included fields
- Column order
- Filtered indexes
- Complicated index types (xml indexes, etc)
You will be much better off either scripting these out in SSMS or using the .NET SMO framework for this.
To appropriately account for all the above issues will require querying a large number of system tables and using CURSORs, WHILE loops, or other iterative constructs to get things in the right order.
It ain't pretty.
SELECT *script but you won't catch things like keys, constraints, etc – JNK♦ Nov 16 '11 at 15:42