An existing database has a large number of tables stored in the PRIMARY filegroup. I want to move theses tables and their indexes on different filegroups automatically, depending on the "prefix" of the table name.
for example, with 5 tables named like this :
ABC_XXXX
ABC_YYYY
DEF_ZZZZ
DEF_TTTT
GHI_UUUU
All tables beginning by ABC
should be moved to filegroup FG1
, DEF
to filegroup FG2
and other tables to filegroup DEFAULT
.
This can be done using the command CREATE INDEX
:
CREATE (UNIQUE|CLUSTERED|) INDEX <Index Name> ON <Table Name>(<Index Columns>)
WITH (DROP_EXISTING = ON) ON <New Filegroup>
The biggest problem with this command is to retrieve the columns of each index in their proper order.
Best Answer
There are a lot of things you are leaving out of your description, which the script will need to accommodate for - is the index a primary key or a unique constraint? are any of the columns descending? is the index filtered? does it have any INCLUDE columns? While you can certainly generate a script manually, why not use the Generate Scripts wizard?
Now you have a query window with all of your scripts, you'll have to remove some and do some hand-massaging of others, but for the indexes that aren't part of the PK you should simply be able to search and replace for
DROP_EXISTING = OFF
toDROP_EXISTING = ON
and then swap out[PRIMARY]
forFG1
...Here is a script that uses
sys.indexes
,sys.columns
, andsys.index_columns
- it creates a unique index in the case where an explicit primary key existed (since you haven't provided the "re-create PK withDROP_EXISTING
" syntax I've asked for). This deals with include columns, fill factors, puts the columns in the correct order and even makes sure to build the unique/clustered indexes first.For completeness, here is a script that adds
sys.partitions
and several SQL Server 2008-specific features such as filtered indexes and data compression.