I want to truncate multiple tables. I know that it isn't possible in the same way that DELETE
will delete the rows from multiple tables.
In this question truncate multi tables IndoKnight provides the OP-designated best answer. I want to try that. However, I get a syntax error at:
TRUNCATE TABLE @tableName
To troubleshoot I tried printing the variables because when I first tried using TRUNCATE TABLE
I needed to include the database name and schema (e.g. NuggetDemoDB.dbo.tablename
) to get it to work. I CAN print the variable @tableList
. But I CANNOT print @tableName
.
DECLARE @delimiter CHAR(1),
@tableList VARCHAR(MAX),
@tableName VARCHAR(20),
@currLen INT
SET @delimiter = ','
SET @tableList = 'Employees,Products,Sales'
--PRINT @tableList
WHILE LEN(@tableList) > 0
BEGIN
SELECT @currLen =
(
CASE charindex( @delimiter, @tableList )
WHEN 0 THEN len( @tableList )
ELSE ( charindex( @delimiter, @tableList ) -1 )
END
)
SET @tableName = SUBSTRING (@tableList,1,@currLen )
--PRINT @tableName
TRUNCATE TABLE @tableName
SELECT tableList =
(
CASE ( len( @tableList ) - @currLen )
WHEN 0 THEN ''
ELSE right( @tableList, len( @tableList ) - @currLen - 1 )
END
)
END
Edit: Fixed the table list to remove the extra "Sales" from the list of tables and added "Employees".