Dynamically Pass a Table Name to TRUNCATE TABLE

Here’s a simple query that shows you how to dynamically pass a Table Name to the TRUNCATE TABLE command

USE YOURDB
GO
DECLARE
@tbl varchar(30) = 'YourTableName'
DECLARE @dynSQL varchar(50)

SET @dynSQL = 'TRUNCATE TABLE ' + @tbl

EXEC (@dynSQL)

You can even create a Stored Procedure and use this code. The only difference will be that ‘YourTableName’ will get replaced with a parameter of the StoredProcedure containing the Table Name

2 comments: