Table variables do not support TRUNCATE
syntax - the only way of truncating them is implicitly by letting them fall out of scope.
Both temporary tables and table variables can be cached when used in stored procedures and the below may well end up with the same table variable being used after truncation rather than an actual drop and create
CREATE PROC dbo.foo @start INT
AS
BEGIN
DECLARE @tableVariable TABLE (
id INT,
value VARCHAR(20))
INSERT INTO @tableVariable
(id,
value)
SELECT id,
value
FROM xTable
WHERE id = @start;
--Use @tableVariable
END
GO
WHILE @start <= @stop
BEGIN
EXEC dbo.foo @start
SET @start = @start + 1
END
Of course a far easier alternative would be to switch to using a #temp
table instead as that supports TRUNCATE
directly.
DML on both table variables and temp tables writes to the tempdb
transaction log. Whether or not it is worth switching to TRUNCATE
rather than DELETE
depends on the size of data involved. TRUNCATE
will just log the page deallocations. DELETE
will log the actual deleted values. One other difference between the two is that TRUNCATE
deallocates the last page from the table and DELETE
doesn't. If only a small quantity of data is inserted and deleted in each loop iteration then the overhead from logging the deleted rows can be less than the overhead from constantly deallocating and reallocating the single page in the table.
Conversely if you will be inserting and deleting large amounts of data on each iteration you may find that TRUNCATE
not only makes the operation of deleting all rows more efficient but also can benefit the subsequent insert statement.