patternsqlMinor
Programmatically copy index from one table to another, via a stored procedure?
Viewed 0 times
storedtableprocedureoneviaanotherindexfromprogrammaticallycopy
Problem
I use a stored procedure to copy the tables from one database to the other database. Right now it does
I would like to copy the index from the original table as well. What would be the best way to go about this ?
insert into copy
select * from originalI would like to copy the index from the original table as well. What would be the best way to go about this ?
Solution
This is a really complicated thing to do in SQL code. It's complicated because indexes have so many options. Potential issues/complications:
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
It ain't pretty.
- 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.
Context
StackExchange Database Administrators Q#7977, answer score: 7
Revisions (0)
No revisions yet.