Admin User Feb,08 2017
The following code demonstrates how to create a temporary table.
CREATE TABLE #TempEmployee(employeeID int,employeeName varchar(100));
This table is automatically dropped when the connection session is closed.
Foreign key relations cannot be applied to temp tables.
Optionally you may drop the table at the end of its use. It is a good practice to drop any temporary table after use.
When you create a temporary table it will be created in tempdb. At the time of table creation the tempdb is locked and hence there is some overhead involved using this.
In SQL Server 2000 or higher, one can take advantage of the new TABLE variable type. These are similar to temporary tables except with more flexibility and they always stay in memory.
The syntax to define a table variable is as follows:
DECLARE TABLE @TempEmployee(employeeID int,employeeName varchar(100));
Querying table variables is very fast as there are no disk reads needed.
Table variables cannot be dropped as they are automatically removed when they are out of scope
All the data in table variables is stored in server’s memory. So if there is huge data then it is not recommended to use table variables to avoid memory overhead.
Note : If you have less than 100 rows generally use a table variable. Otherwise use a temporary table. This is because SQL Server won’t create statistics on table variables.