Search code examples
sql-serversql-server-2008switch-statementdatabase-partitioning

SQL Server Switch more than one Partition at once


I have 100 parititons in a table that I need to switch to its corresponding stage table (on the same FG and with aligned indexes) Currently i m using the query below

Alter Table MS_PROD Switch Partition 5 TO MS_Stage PARTITION 5

I m ending up doing this for all 100 partitions, is there a fast way to switch all partitons in parallel.


Solution

  • Not that I'm aware of. What I'd typically do is place the switch inside the loop. Something like this:

    DECLARE @Partitions TABLE (PartitionId int PRIMARY KEY CLUSTERED);
    DECLARE @PartitionId INT;
    
    INSERT @Partitions(PartitionId)
        SELECT 
            prv.boundary_id PartitionId
        FROM sys.partition_functions AS pf 
        INNER JOIN sys.partition_range_values prv ON prv.function_id=pf.function_id
        WHERE (pf.name=N'PartitionFunctionName');
    
    WHILE EXISTS (SELECT NULL FROM @Partitions)
        BEGIN
    
            SELECT TOP 1 @PartitionId = PartitionId FROM @Partitions;
    
            ALTER TABLE MS_PROD SWITCH PARTITION @PartitionId TO MS_Stage PARTITION @PartitionId;
    
            RAISERROR('Switched PartitionId %d to Stage',0,1,@PartitionId) WITH NOWAIT;
    
            DELETE @Partitions WHERE PartitionId = @PartitionId;
    
        END