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)
Thank this author by sharing:
By Vidyadhar Pandekar,
- 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.
From SQL Server query analyzer-
Exec dbo.truncate_partition 'SchemaName','TableName', PartitionNumber
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
cluster group won't move to primary node
Wouldn't be great if you could truncate any partition of a partitioned table with one T-SQL statemen...
Script to duplicate structure, switch or truncate choosen partitions of a table
Partition key should be part of Primary key