Temporary Tables vs Table Variable in Sql Server

 Sure, I’d be happy to explain the differences between temporary tables and table variables in SQL Server.

Temporary Tables:

  • Temporary tables are created in tempdb.
  • They act like regular tables, so you can perform operations like CREATE INDEX, apply constraints, defaults, and referential integrity.
  • They are visible only to the current session.
  • If created inside a stored procedure, they are destroyed upon completion of the stored procedure.
  • They can result in stored procedures being recompiled.

Table Variables:

  • Table variables are also created in tempdb, but they are also stored in memory.
  • They cannot be involved in transactions, logging, or locking.
  • They don’t participate in transactions and SELECTs are implicitly with NOLOCK.
  • They don’t result in stored procedures being recompiled.
  • They can have indexes by using PRIMARY KEY or UNIQUE constraints.
  • They exist for a particular batch of query execution and get dropped once it comes out of the batch.

As a rule of thumb, for small to medium volumes of data and simple usage scenarios, you should use table variables. However, if you have large amounts of data for which accessing by index will be faster, then temporary tables are a good option.



Examples of how to create a temporary table and a table variable in SQL Server.

Temporary Table:

CREATE TABLE #TempTable
(
    EmployeeID INT,
    Name NVARCHAR(50),
    Salary DECIMAL(10, 2)
);

In this example, #TempTable is a local temporary table. It is visible only in the current session.

Global Temporary Table:

CREATE TABLE ##GlobalTempTable
(
    EmployeeID INT,
    Name NVARCHAR(50),
    Salary DECIMAL(10, 2)
);

In this example, ##GlobalTempTable is a global temporary table. It is visible to all sessions until the last session referencing it is closed.

Table Variable:

DECLARE @TableVariable TABLE
(
    EmployeeID INT,
    Name NVARCHAR(50),
    Salary DECIMAL(10, 2)
);

In this example, @TableVariable is a table variable. It is visible only in the current batch or procedure.

Please note that while you can create global temporary tables, you cannot create global table variables. The scope of a table variable is limited to the current batch or procedure.


Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form