-- Create clustered columnstore index on error log (Enterprise 2012+) CREATE CLUSTERED COLUMNSTORE INDEX CCI_ErrorLog ON dbo.ErrorLog WITH (MAXDOP = 4, COMPRESSION_DELAY = 0); GO -- Create partitioned table (Enterprise feature) CREATE PARTITION FUNCTION pf_DateRange (DATETIME) AS RANGE RIGHT FOR VALUES ( '2024-01-01', '2024-04-01', '2024-07-01', '2024-10-01', '2025-01-01' ); CREATE PARTITION SCHEME ps_DateRange AS PARTITION pf_DateRange ALL TO ([PRIMARY]);
IF @ObjectID IS NULL BEGIN RAISERROR('Table not found', 16, 1); RETURN; END; sql server 2012 enterprise
WHILE @PartitionNumber <= @MaxPartition BEGIN BEGIN TRY -- ONLINE rebuild with compression (Enterprise only) SET @SQL = ' ALTER INDEX ALL ON ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + ' REBUILD PARTITION = ' + CAST(@PartitionNumber AS NVARCHAR(10)) + ' WITH ( ONLINE = ON, SORT_IN_TEMPDB = ON, MAXDOP = ' + CAST(@MaxDOP AS NVARCHAR(2)) + ', DATA_COMPRESSION = ' + @CompressionType + ', WAIT_AT_LOW_PRIORITY ( MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDurationMinutes AS NVARCHAR(3)) + ' MINUTES, ABORT_AFTER_WAIT = BLOCKERS ) );'; PRINT 'Processing partition ' + CAST(@PartitionNumber AS VARCHAR) + ' of ' + CAST(@MaxPartition AS VARCHAR); EXEC sp_executesql @SQL; -- Update log UPDATE dbo.IndexMaintenanceLog SET PartitionsProcessed = @PartitionNumber, LastProcessedTime = GETDATE() WHERE TableName = @SchemaName + '.' + @TableName AND Status = 'Running'; END TRY BEGIN CATCH -- Log error INSERT INTO dbo.ErrorLog (ProcedureName, ErrorMessage, ErrorDate) VALUES ('Enterprise_OptimizeTablePartitions', ERROR_MESSAGE(), GETDATE()); RAISERROR('Failed on partition %d: %s', 16, 1, @PartitionNumber, ERROR_MESSAGE()); END CATCH; SET @PartitionNumber = @PartitionNumber + 1; END; -- Create clustered columnstore index on error log