1. How Procedure works-
- Procedure has following mandatory input parameters
a. Schema name of the table
b. Table Name
c. Number of the partition to be truncated
- Step1- Creates the staging table with the schema structure matching with source or partitioned table.
- Step2- Identifies if the clustered primary key is there or clustered index without primary key is there on source partitioned table. If Clustered PK is there, it creates the same clustered primary key on target table else it creates dummy clustered primary key on target table.
- Step3- Identifies file-group of the partition to be truncated
- Step4- Moves target staging table to the same file group as file group of partition of source table. ["ALTER TABLE TABLE_NAME DROP CONSTRAINT with MOVE TO file-group" command is used for moving table from one file group to another. Constraint should be clustered]
- Step5- If there is clustered index on the source partitioned table same index is created on staging table. This requirement for SWITH PARTITION statement.
- Step6- Truncates the table partition using ALTER TABLE SWITH PARTITION statement. This moves the data of truncated partition from partitioned table to staging table
- Step7- Drops the staging table which is not required now
- Step8- Error and transaction handling.
2. How to execute the truncate_partition?
From SQL Server query analyzer-
Exec dbo.truncate_partition 'SchemaName','TableName', PartitionNumber
3. Script is tested and works for following scenarios-
1 No Primary key and No Clustered Index
2 Clustered Primary key
3 No Primary key and Clustered Index
4 Non Clustered Primary key
Note: Please provide the further feedback to improve the script
10thFeb 2010- Added functionality, truncate partition works if source partitioned table or a particular partition is compressed