MSSQL Rebuild(重建)索引

前的项目是做数据库的归档,在每次archive后都需要对原数据库的索引进行rebuild,以减少索引碎片,于是乎就自己写了一段sql:

DECLARE @tablename VARCHAR(50)
DECLARE @indexname VARCHAR(50)
DECLARE @cmdsql NVARCHAR(MAX)
DECLARE index_cursor CURSOR
FOR
SELECT  OBJECT_NAME(object_id) AS Table_Name ,
        name
FROM    sys.indexes
WHERE   name IS NOT NULL
        AND OBJECT_NAME(object_id) IN ( SELECT  name
                                        FROM    sys.tables )
          OPEN index_cursor
FETCH NEXT FROM index_cursor
INTO @tablename,@indexname

WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @cmdsql ='ALTER INDEX ['+@indexname+'] ON [dbo].['+@tablename+'] REBUILD WITH ( PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, SORT_IN_TEMPDB = OFF, ONLINE = OFF )'
        EXECUTE sp_executesql @cmdsql
        PRINT @cmdsql
        FETCH NEXT FROM index_cursor
 INTO @tablename,@indexname
    END
CLOSE index_cursor
DEALLOCATE index_cursor

希望对大家有帮助!

posted on 2013-07-25 13:47  dz45693  阅读(2419)  评论(0编辑  收藏  举报

导航