Temporary Tables are a great feature that lets you store and process intermediate results by using the same selection, update, and join capabilities that you can use with typical SQL Server tables. The temporary tables could be very useful in some cases to keep temporary data.
There are mainly two types of Temporary Tables-Local & Global Temporary Tables.
1. Local Temporary Table:
These tables are only available for the session that has created them. Once the session is terminated, these tables are automatically deleted. They can be also be deleted explicitly.
2. Global Temporary Table:
These tables are available for all the sessions and users. They are not deleted until the last session using them is terminated. Similar to local Temporary Table, a user can delete them explicitly.
The syntax for creating Temporary Table.
Scope. Unlike the majority of the other data types in SQL Server, you cannot use a table variable as an input or an output parameter. In fact, a table variable is scoped to the stored procedure, batch, or user-defined function just like any local variable you create with a DECLARE statement.
They can be declared in batch or stored procedure. Unlike Temporary Tables, they cannot be dropped explicitly. Once the batch execution is finished, the Table Variables are dropped automatically.
The syntax for Table Variable.
Differences Between Temp tables and Table Variables in SQL Server
In this section, we have listed the major differences between Temporary Tables and Table Variables. They are
|Terms||Temporary Table||Table Variable|
|Storage Location||The temporary tables are stored in tempdb database of SQL server.||The Table Variables are stored in both the memory and the disk in the tempdb database.|
|User Defined Functions||They are not allowed in the user-defined functions.||The table variables can be used in user-defined functions.|
|Transactions||They support the explicit transactions that are defined by the user.||They do not participate in the transactions that have been explicitly defined by the user.|
|Indexes||Local and Global Temporary Tables support creation of indexes on them in order to increase the performance.||Table Variables do not allow creation of indexes on them.|
|Locking||Since the Temporary Tables are physical tables, while reading from the table, SQL Optimizer puts a read lock on the table.||Since the Table Variables are partially stored in the memory, they cannot be accessed by any other user or process that the current user. Therefore, no read lock is put on the Table Variable.|