存储过程如下:

USE [SCC_Test_FileGroupAndIndex]
GO
/****** Object:  StoredProcedure [dbo].[sp_MoveTable]    Script Date: 2015/3/5 11:16:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*移动表数据到别的文件组 2008-12-29*/
ALTER PROC [dbo].[sp_MoveTable]
    (
      @objectname sysname ,
      @NewFileGroup sysname = NULL
    )
AS
    SET NOCOUNT ON
    DECLARE @objectid INT

    SELECT  @objectid = object_id ,
            @objectname = name
    FROM    sys.objects AS a
    WHERE   name = @objectname
            AND Type = 'U'
            AND is_ms_shipped = 0
            AND NOT EXISTS ( SELECT 1
                             FROM   sys.extended_properties
                             WHERE  major_id = a.object_id
                                    AND minor_id = 0
                                    AND class = 1
                                    AND name = N'microsoft_database_tools_support' )
    IF @objectid IS NULL
        BEGIN
            --RAISERROR 50001 N'无效的表名!'
            RAISERROR (N'无效的表名', -- Message text.
           10,           -- Severity,
           1            -- State,
          );    -- First argument supplies the string.
            RETURN
        END

    IF FILEGROUP_ID(@NewFileGroup) IS NULL
        AND @NewFileGroup > ''
        BEGIN
           -- RAISERROR 50001 N'错误的文件组!'
            RAISERROR (N'错误的文件组', -- Message text.
           10,           -- Severity,
           2            -- State,
         );    -- First argument supplies the string.
            RETURN
        END

    IF @NewFileGroup IS NULL
        SELECT  @NewFileGroup = name
        FROM    sys.filegroups
        WHERE   is_default = 1

    IF EXISTS ( SELECT  1
                FROM    sys.indexes AS a
                        INNER JOIN sys.filegroups AS b ON b.data_space_id = a.data_space_id
                WHERE   a.object_id = @objectid
                        AND b.name = @NewFileGroup
                        AND ( a.type = 0
                              OR is_primary_key = 1
                            ) )
        BEGIN
            PRINT N'表' + @objectname + N'已在文件组' + @NewFileGroup + N' .不需要移动! '
            RETURN
        END

    DECLARE @sql NVARCHAR(4000) ,
        @Enter NVARCHAR(20) ,
        @PrimaryKey sysname

    SELECT  @sql = '' ,
            @Enter = CHAR(13) + CHAR(10)

--删除主键、外键、索引
    SELECT  @sql = @sql + 'Alter Table '
            + QUOTENAME(OBJECT_NAME(a.parent_object_id)) + ' Drop Constraint '
            + QUOTENAME(a.name) + @Enter
    FROM    sys.Foreign_keys AS a
    WHERE   a.referenced_object_id = @objectid

    SELECT  @sql = @sql
            + CASE WHEN b.object_id IS NOT NULL
                   THEN 'Alter Table ' + QUOTENAME(@objectname)
                        + ' Drop Constraint ' + QUOTENAME(a.name)
                        + CASE b.Type
                            WHEN 'PK'
                            THEN ' With (Move To ' + QUOTENAME(@NewFileGroup)
                                 + ')'
                            ELSE ''
                          END
                   ELSE 'Drop Index ' + QUOTENAME(a.name) + '.'
                        + QUOTENAME(@objectname)
              END + @Enter
    FROM    sys.indexes AS a
            LEFT OUTER JOIN sys.objects AS b ON b.parent_object_id = a.object_id
                                                AND b.Type IN ( 'PK', 'UQ' )
                                                AND b.name = a.name
    WHERE   a.object_id = @objectid
            AND a.name IS NOT NULL

    IF NOT EXISTS ( SELECT  *
                    FROM    sys.indexes
                    WHERE   object_id = @objectid
                            AND is_primary_key = 1 )
        BEGIN
            SET @PrimaryKey = 'ID' + REPLACE(NEWID(), '-', '')
--创建主键(在表没有主键的情况)
            SET @sql = @sql + 'Alter Table ' + QUOTENAME(@objectname)
                + ' Add ' + @PrimaryKey
                + ' uniqueidentifier Not Null ,Constraint DF_' + @objectname
                + '_' + @PrimaryKey + ' Default(newid()) For ' + @PrimaryKey
                + '' + ',Constraint PK_' + @objectname + '_' + @PrimaryKey
                + ' Primary Key (' + @PrimaryKey + ' Asc)' + @Enter
--删除主键
            SET @sql = @sql + 'Alter Table ' + QUOTENAME(@objectname)
                + ' Drop Constraint PK_' + @objectname + '_' + @PrimaryKey
                + ' With (Move To ' + QUOTENAME(@NewFileGroup) + ')' + @Enter
            SET @sql = @sql + 'Alter Table ' + QUOTENAME(@objectname)
                + ' Drop Constraint DF_' + @objectname + '_' + @PrimaryKey
                + @Enter
            SET @sql = @sql + 'Alter Table ' + QUOTENAME(@objectname)
                + ' Drop Column ' + @PrimaryKey + @Enter
        END

--创建主键、外键、索引
    SELECT  @sql = @sql
            + CASE WHEN b.object_id IS NOT NULL
                   THEN 'Alter Table ' + QUOTENAME(@objectname)
                        + ' Add Constraint ' + QUOTENAME(a.name)
                        + CASE a.is_primary_key
                            WHEN 1 THEN ' Primary Key '
                            ELSE 'Unique '
                          END + '(' + c.x + ')'
                   ELSE 'Create Index ' + CASE a.is_unique
                                            WHEN 1 THEN 'Unique '
                                            ELSE ''
                                          END + CASE a.type
                                                  WHEN 1 THEN 'Clustered '
                                                  ELSE ''
                                                END + QUOTENAME(a.name)
                        + ' On ' + QUOTENAME(@objectname) + '(' + c.x + ')'
                        + ISNULL(' Include(' + d.x + ')', '')
              END + @Enter
    FROM    sys.indexes AS a
            LEFT OUTER JOIN sys.objects AS b ON b.parent_object_id = a.object_id
                                                AND b.Type IN ( 'PK', 'UQ' )
                                                AND b.name = a.name
            OUTER APPLY ( SELECT    x = STUFF(( SELECT  ',' + QUOTENAME(y.name)
                                                        + CASE x.is_descending_key
                                                            WHEN 1
                                                            THEN ' Desc'
                                                            ELSE ' Asc'
                                                          END
                                                FROM    sys.index_columns AS x
                                                        INNER JOIN sys.columns
                                                        AS y ON y.object_id = x.object_id
                                                              AND x.column_id = y.column_id
                                                WHERE   x.object_id = a.object_id
                                                        AND x.index_id = a.index_id
                                                        AND x.is_included_column = 0
                                              FOR
                                                XML PATH('')
                                              ), 1, 1, '')
                        ) AS c
            OUTER APPLY ( SELECT    x = STUFF(( SELECT  ',' + QUOTENAME(y.name)
                                                FROM    sys.index_columns AS x
                                                        INNER JOIN sys.columns
                                                        AS y ON y.object_id = x.object_id
                                                              AND x.column_id = y.column_id
                                                WHERE   x.object_id = a.object_id
                                                        AND x.index_id = a.index_id
                                                        AND x.is_included_column = 1
                                              FOR
                                                XML PATH('')
                                              ), 1, 1, '')
                        ) AS d
    WHERE   a.object_id = @objectid
            AND a.name IS NOT NULL

    SELECT  @sql = @sql + 'Alter Table '
            + QUOTENAME(OBJECT_NAME(a.parent_object_id)) + ' Add Constraint '
            + QUOTENAME(a.name) + ' Foreign Key (' + b.x + ') References '
            + QUOTENAME(@objectname) + '(' + c.x + ')' + @Enter
    FROM    sys.Foreign_keys AS a
            OUTER APPLY ( SELECT    x = STUFF(( SELECT  ',' + QUOTENAME(y.name)
                                                FROM    sys.Foreign_key_columns
                                                        AS x
                                                        INNER JOIN sys.columns
                                                        AS y ON y.object_id = x.parent_object_id
                                                              AND y.column_id = x.parent_column_id
                                                WHERE   x.constraint_object_id = a.object_id
                                              FOR
                                                XML PATH('')
                                              ), 1, 1, '')
                        ) AS b
            OUTER APPLY ( SELECT    x = STUFF(( SELECT  ',' + QUOTENAME(y.name)
                                                FROM    sys.Foreign_key_columns
                                                        AS x
                                                        INNER JOIN sys.columns
                                                        AS y ON y.object_id = x.referenced_object_id
                                                              AND y.column_id = x.referenced_column_id
                                                WHERE   x.constraint_object_id = a.object_id
                                              FOR
                                                XML PATH('')
                                              ), 1, 1, '')
                        ) AS c
    WHERE   a.referenced_object_id = @objectid

--执行脚本
    BEGIN TRY
        BEGIN TRAN
        EXEC(@sql)
        COMMIT TRAN
        PRINT N'表' + @objectname + N'数据移动到到文件组' + @NewFileGroup + N' .成功! '
    END TRY
    BEGIN CATCH
        DECLARE @Error NVARCHAR(1024)
        SET @Error = ERROR_MESSAGE()
        --RAISERROR 50001 @Error
        RAISERROR (@Error, -- Message text.
                10, -- Severity.
                3 -- State.
               );
        PRINT N'表' + @objectname + N'数据移动到到文件组' + @NewFileGroup + N' .失败! ';
        PRINT N'报错语句:' + @sql;
        ROLLBACK TRAN
    END CATCH

 

 

使用示例:

EXEC sp_MoveTable TblStudents, 'StudentsFileGroup';

 

报错处理:

由于有时候执行删除索引移动表的时候会报错,报错的语句如下:

ALTER TABLE [TblStudents] DROP CONSTRAINT [PK_TblStudentsIndex] WITH (MOVE TO [Schedule]);
ALTER TABLE [TblStudents] ADD CONSTRAINT [PK_TblStudentsIndex] PRIMARY KEY ([OID] ASC);

 

可以改成如下语句运行:

ALTER TABLE [TblStudents] DROP CONSTRAINT [PK_TblStudentsIndex];
ALTER TABLE [TblStudents] ADD CONSTRAINT [PK_TblStudentsIndex] PRIMARY KEY ([OID] ASC);

ALTER TABLE [TblStudents] DROP CONSTRAINT [PK_TblStudentsIndex] WITH (MOVE TO [Schedule]);
ALTER TABLE [TblStudents] ADD CONSTRAINT [PK_TblStudentsIndex] PRIMARY KEY ([OID] ASC);

sql server 移动表到文件组的更多相关文章

  1. sql server迁移数据(文件组之间的互相迁移与 文件组内文件的互相迁移)

    转自:https://www.cnblogs.com/lyhabc/p/3504380.html?utm_source=tuicool SQLSERVER将数据移到另一个文件组之后清空文件组并删除文件 ...

  2. sql server 备份与恢复系列六 文件组备份与还原

    一. 概述 文件备份是指备份一个或多个文件或文件组中的所有数据.使用文件备份能够只还原损坏的文件,而不用还原数据库的其余部份,从而加快恢复速度.例如,如果数据库由位于不同磁盘上的若干文件组成,在其中一 ...

  3. 关于SQL Server中分区表的文件与文件组的删除(转)

    在SQL Server中对表进行分区管理时,必定涉及到文件与文件组,关于文件与文件组如何创建在网上资料很多,我博客里也有两篇相关转载文件,可以看看,我这就不再细述,这里主要讲几个一般网上很少讲到的东西 ...

  4. SQL Server 创建表分区

    原文:SQL Server 创建表分区 先准备测试表 CREATE TABLE [dbo].[Employee] ( EmployeeNo ,) PRIMARY KEY, EmployeeName ) ...

  5. Sql server 系统表

    sql server系统表详细说明 SQL Server 用户库中系统表说明 名称 说明 备注 syscolumns 每个表和视图中的每列在表中占一行,存储过程中的每个参数在表中也占一行.   sys ...

  6. sql server系统表和视图相关的语句

    一.系统表 数据字典的详细信息请查SQL SERVER BOL,这里仅列出一部分. 1.1.sysservers 1.查看所有本地服务器及链接服务器 select * from master..sys ...

  7. SQL Server 2008 表分区的含义

    https://www.cnblogs.com/knowledgesea/p/3696912.html 继续看这个文档 http://www.360doc.com/content/16/0104/11 ...

  8. SQL Server系统表介绍与使用

    关于SQL Server数据库的一切信息都保存在它的系统表格里.我怀疑你是否花过比较多的时间来检查系统表格,因为你总是忙于用户表格.但是,你可能需要偶尔做一点不同寻常的事,例如数据库所有的触发器.你可 ...

  9. SQL Server单表已700w+将普通表转换成分区表1

    最近项目中,某个表数据量爆发时增长,单表已700w+,读写性能急剧下降,所以考虑加入分区表以解燃眉之急,后续还是要分表分库,当然这是后话.下面简要说一下将普通表转为分区表的步骤.   一.创建文件组 ...

随机推荐

  1. Cobub Razor

    Cobub Razor - 开源移动应用统计分析平台

  2. UE正则表达式查找和替换(将【,;】)替换为换行

  3. Java custom annotations

    Custom annotation definition is similar as Interface, just with @ in front. Annotation interface its ...

  4. flexible.js

    关于rem小数点 flexible.js http://blog.163.com/hongshaoguoguo@126/blog/static/180469812015219101346170/ ht ...

  5. 14、C#基础整理(函数)

    函数 1.概念:是一个带有输入参数.输出参数.返回值的代码块. 2.写法: 修饰符  返回值类型  函数名(输入参数,输入参数) { 方法段 return 返回值; } 3.注释: (1)输入参数格式 ...

  6. JNI c++ 调用 java

    ----------------------------------------------c++--------------------------------------- #include &q ...

  7. 《深入浅出Node.js》第2章 模块机制

    @by Ruth92(转载请注明出处) 第2章 模块机制 JavaScript 先天缺乏的功能:模块. 一.CommonJS 规范: JavaScript 规范的缺陷:1)没有模块系统:2)标准库较少 ...

  8. Core Java Volume I — 4.10. Class Design Hints

    4.10. Class Design HintsWithout trying to be comprehensive or tedious, we want to end this chapter w ...

  9. 如何为libs目录下的jar包关联源代码

    以前,我们可以为lib目录下的jar包关联源代码,但是现在似乎不行了. 下面是一篇讲述此问题解决方法的文章: How to attach javadoc or sources to jars in l ...

  10. [转载]在Android C/C++层添加LOG调试

    原文地址:C/C++层添加LOG调试">在Android C/C++层添加LOG调试作者:谢轩昂 在Android C/C++层添加LOG调试,并且在Logcat中输出的方法 第一步: ...