Wednesday, May 16, 2018

Difference between #temptable and ##TempTable and table variable?

Local Temporary tables

Local temp tables are only available to the current connection for the user; and they are automatically deleted when the user disconnects from instances. Local temporary table name is stared with hash ("#") sign. scope of Local Temporary table is only bounded with the current connection of current user.

CREATE TABLE #TempTable(
 ID int,
 Name varchar(50))

Global Temporary tables

Global Temporary tables name starts with a double hash ("##"). Once this table has been created by a connection, like a permanent table it is then available to any user by any connection. It can only be deleted once all connections have been closed. Global temporary tables are visible to all SQL Server connections. When you create one of these, all the users can see it.

CREATE TABLE ##GlobalTempTable(
 ID int,
 Name varchar(50))

Table variables in T-SQL

Microsoft introduced table variables with SQL Server 2000 as an alternative to using temporary tables. In many cases a table variable can outperform a solution using a temporary table
Table variables store a set of records, so naturally the declaration syntax looks very similar to a CREATE TABLE statement, as you can see in the following example:

DECLARE @UserTable TABLE
( ID int,
  Name varchar(50))

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. The variable will no longer exist after the procedure exits - there will be no table to clean up with a DROP statement.

Because of the well-defined scope, a table variable will generally use fewer resources than a temporary table. Transactions touching table variables only last for the duration of the update on the table variable, so there is less locking and logging overhead.
Using a temporary table inside of a stored procedure may result in additional re-compilations of the stored procedure. Table variables can often avoid this recompilation hit.

No comments:

Post a Comment