Sunday, 27 September 2015

Difference between Temporary Table and Table Variable

Below list is major difference between Temporary Table and Table Variable Datatype in Sql Server;


Temporary Table
Table Variable
Change of Structure
We can change
 the structure of temporary table after creation of it,
 we can use DDL statements ALTER, CREATE, DROP
We can’t change the structure of table variable. It doesn’t support DDL Statement like ALTER, CREATE, DROP.
User defined Function
User defined function not allowed temporary table.
Table variables are allowed in User Defined functions.
Transaction
Temporary table support the explicit transactions. .
It not supports the explicit transactions.
Index
 Temporary table allow adding explicit indexes after declarations.
Table variables not allow adding explicit indexes after declarations.
Scope
Scope of the Local Temporary Table is in the session in which it created and they are dropped automatically once the session ends and we can also drop them explicitly.
 Scope of the Table variable is the Batch or Stored Procedure in which it is declared. and they can’t be dropped explicitly,
Syntax
Creating the temporary Table

-- Create Temporary Table
CREATE TABLE Employee (EmpId INT, Name VARCHAR(50))

--Insert records
INSERT INTO #Employee VALUES(1,'BOB')

--Reterive the records
SELECT * FROM #Employe

--DROP Temporary Table
DROP TABLE #Employee
Using Table variables;

-- Create Table Variable
DECLARE @Employee TABLE
(
 Id INT,
 Name VARCHAR(50)  
)
--Insert Two records
INSERT INTO @Employee VALUES(1,'BOb')
--Reterive the records
SELECT * FROM @Employee
GO



No comments:

Post a Comment

Others

You will like to read it