r/dbatools • u/oldemanry23 • Apr 05 '24
Function built to Copy Indexes from one clone table to another?
I'm a bit new to dbatools but I have been using some AI-assisted searching along with their incredible documentation page, and cannot seem to find a means to copy indexes over. AI engines all recommend using Copy-DbaDbTableData with using -KeepIdentity flag, but upon some very quick and clear tests, this does not default to including indexes.
SSIS and SSMS both have Import/Export Data tasks and I'm familiar that SSIS's Copy Objects has Indexes=T/F, but they build the indexes on the table before data inserts, and for obvious reasons I want to avoid that workflow and wish to do a table copy, then index, per table.
I'm not opposed to writing it myself, but I figured I'd check the community before committing that time!
3
u/alinroc Apr 08 '24 edited Apr 08 '24
Fairly basic example but I think you'll get the idea. I'm using a copy of the Stack Overflow database
Line by line:
Get the
Poststable from the source databaseCreate the table in the target database by using the SMO
Script()method on theTableobject to generate thecreate tablescript (and then execute it)Create the indexes on the target database's (empty) copy of the table by using the SMO
Script()method on theIndexobject(s) to generate thecreate indexscript (and then execute it)From here, you can use
Copy-DbaDbTableData