如何将现有索引和主键移动到SQL SERVER中的辅助文件组

时间:2014-07-07 05:51:27

标签: sql sql-server-2008 indexing primary-key filegroup

所有索引和主键都是在主文件(.mdf)中创建的。 有没有办法将所有索引和主键移动到辅助文件组(.ndf)??

2 个答案:

答案 0 :(得分:1)

使用以下查询:

DECLARE @SchemaName NVARCHAR(300),
        @ObjectName NVARCHAR(300),
        @IndexName NVARCHAR(300),
        @Columns NVARCHAR(MAX),
        @IncludeColumns NVARCHAR(MAX),
        @Command NVARCHAR(MAX)

DECLARE IndexCursor CURSOR FOR
    SELECT SCHEMA_NAME(o.schema_id),OBJECT_NAME(o.object_id), i.name, 
            STUFF((SELECT ',['+c.name+']'
            FROM sys.index_columns ic 
            INNER JOIN sys.columns c ON c.column_id = ic.column_id AND c.object_id = ic.object_id
            WHERE ic.object_id = i.object_id
                AND ic.index_id = i.index_id
                AND ic.is_included_column=0 
            ORDER BY ic.key_ordinal
            FOR XML PATH('')
            ),1,1,'') IndexColumn,
            STUFF((SELECT ',['+c.name+']'
            FROM sys.index_columns ic 
            INNER JOIN sys.columns c ON c.column_id = ic.column_id AND c.object_id = ic.object_id
            WHERE ic.object_id = i.object_id
                AND ic.index_id = i.index_id
                AND ic.is_included_column=1
            ORDER BY ic.key_ordinal
            FOR XML PATH('')
            ),1,1,'') IncludeColumn,
            i.filter_definition
    FROM sys.indexes i
    INNER JOIN sys.objects o ON o.object_id = i.object_id
    INNER JOIN sys.data_spaces ds ON ds.data_space_id = i.data_space_id
    WHERE ds.name = 'PRIMARY'
        AND OBJECTPROPERTY(i.object_id,'IsUserTable')=1

OPEN IndexCursor
FETCH NEXT FROM IndexCursor INTO @SchemaName, @ObjectName, @IndexName, @Columns, @IncludeColumns
WHILE @@FETCH_STATUS=0 BEGIN

    SET @Command = 'ALTER INDEX ' + @IndexName + ' ON [' + @SchemaName + '].['+@ObjectName+']('+@Columns+') '+ ISNULL('Include ('+@IncludeColumns+')','') + ' ON [YourFileGroupName]'
    EXEC(@Command)

    FETCH NEXT FROM IndexCursor INTO @SchemaName, @ObjectName, @IndexName, @Columns, @IncludeColumns
END
CLOSE IndexCursor
DEALLOCATE IndexCursor

答案 1 :(得分:0)

  1. 您无法使用Management Studio移动使用UNIQUE或PRIMARY KEY约束创建的索引。要移动这些索引,请使用带有Transact-SQL中的(DROP_EXISTING = ON)选项的CREATE INDEX语句。

  2. 如果表具有聚簇索引,则将聚簇索引移动到新文件组会将表移动到该文件组。

  3. 对于分步指导,您可以使用MS documentation.