SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Truncate Table Partition command in SQL Server

By Vidyadhar Pandekar,

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

Script Enhancements-

10thFeb 2010- Added functionality, truncate partition works if source partitioned table or a particular partition is compressed

Total article views: 9104 | Views in the last 30 days: 3
Related Articles

cluster group won't move to primary node

cluster group won't move to primary node


Dynamically Truncate a Partitioned Table

Wouldn't be great if you could truncate any partition of a partitioned table with one T-SQL statemen...


Truncate or switch range of a partitioned table

Script to duplicate structure, switch or truncate choosen partitions of a table





Partition key should be part of Primary key

Partition key should be part of Primary key