How to delete table variables in SQL Server? Should I do this?

I have a table variable in a script (and not a stored procedure). Two questions:

  • How to delete a table variable? Drop Table @varName gives the "Invalid snytax" error.
  • Should I always do this? I heard that this is a good practice. Is it really necessary for small scripts like this?

Here is my code:

Declare @projectList table( name varchar(40) NOT NULL); Insert Into @projectList Values ('BCR-00021') Select * From @projectList Drop Table @projectList -- does not work 
+85
sql sql-server table-variable
Apr 13 '11 at 18:00
source share
5 answers

Table variables are automatically local and automatically discarded - you have nothing to worry about.

+129
Apr 13 '11 at 18:01
source share

Table variables are similar to variables of the int or varchar type.

You do not need to drop them. They have the same scope rules as int or varchar variables

The scope of a variable is the range of Transact-SQL statements that can reference a variable. The volume of a variable lasts from the point that is declared until the end of the batch or stored procedure at which it is declared.

+25
Apr 13 2018-11-18T00:
source share

Just Like TempTables, a local table variable is also created in TempDB. The scope of a table variable is the batch, stored procedure, and statement block in which it is declared. They can be passed as parameters between procedures. They are automatically deleted when you close the session in which you create them.

+3
May 15 '15 at 7:01
source share

But you all forgot to mention that if a table variable is used in a loop, it will need to clear (delete @table) before loading the data again in the loop.

+1
Apr 27 '17 at 21:11
source share

if someone else comes across this ... and you really need to drop it, as in a loop, you can just delete everything from the table variable:

 DELETE FROM @tableVariableName 
0
Aug 02 '17 at 8:28
source share



All Articles