Rebuild a Specific Partition

The following code snippet will enable you to rebuild a specific partition on an index in SQL Server. This is very useful when the table in question is very large and you only want to rebuild the specific partition that you deleted data, inserted or partition switched data into. To rebuild the entire index on very large tables will just take to much time and the SQL Server engine might run out of memory.

    Declare @SqlCommand varchar(2000) = ”
    Declare @SchemaName varchar(3) = ‘dbo’
    Declare @TableName varchar(10) = ‘FactSales’
    Declare @IndexName varchar(50) = ‘CCI_FactSales’
    Declare @PartitionNumber int = (Select Top 1 $partition.pfDaily(‘2015-01-01’) From [dbo].[FactTable])

    Set @SqlCommand = N’ALTER INDEX ‘ + Quotename(@IndexName) + N’ ON ‘ + Quotename(@SchemaName) + N’.’ + Quotename(@TableName) + N’ REBUILD PARTITION = ‘ + Cast(@PartitionNumber As NVarchar(10)) + ‘;’;’

    Exec(@SqlCommand);

You can use this code after the Incremental load on a table to rebuild only the specific partition to ensure the data in the partition is not fragmented.

Feel free to comment or ask a question on this topic

This entry was posted in SQL Server 2008, SQL Server 2012, SQL Server 2014 and tagged , , . Bookmark the permalink.

1 Response to Rebuild a Specific Partition

  1. macguires says:

    Drickus, jou yster!!!

    Liked by 1 person

Leave a comment