Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate/Clear table variable in SQL Server 2008

Is it possible to truncate or flush out a table variable in SQL Server 2008?

declare @tableVariable table (    id int,     value varchar(20) )      while @start <= @stop     begin         insert into @tableVariable(id, value)          select id             , value          from xTable          where id = @start          --Use @tableVariable       --@tableVariable should be flushed out of      -- old values before inserting new  values      set @start = @start + 1  end  
like image 855
shrekDeep Avatar asked Feb 26 '14 15:02

shrekDeep


People also ask

How do I TRUNCATE a table variable in SQL Server?

You can just use DELETE FROM @tableVariable , as described in the accepted answer, to get functionality substantially equivalent to TRUNCATE TABLE (except for the logging - this could certainly be a problem if there were a lot of rows in the variable, or the SQL that created the variable was being run very often).

Can we TRUNCATE table variable?

you can't truncate a table variable. you could either use a temp table or just simply create a new table variable and use it and just let them both fall out of scope at the end.

How do you clear a variable in SQL?

Usage. The DROP VARIABLE statement eliminates a SQL variable that was previously created using the CREATE VARIABLE statement. Variables are automatically eliminated when the database connection is released.

Does TRUNCATE reset the identity?

Truncate command reset the identity to its seed value. It requires more transaction log space than the truncate command. It requires less transaction log space than the truncate command. You require Alter table permissions to truncate a table.


2 Answers

just delete everything

DELETE FROM @tableVariable 
like image 160
peter Avatar answered Sep 21 '22 06:09

peter


No, you cannot TRUNCATE a table variable since it is not a physical table. Deleting it would be faster. See this answer from Aaron Bertrand.

like image 22
TTeeple Avatar answered Sep 22 '22 06:09

TTeeple