Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

Temp Table in SQL Server

by suresh

The temporary or temp table in SQL Server can be created at the run-time and perform all the operations that a regular table can do. There are two types of Temporary Tables in SQL Server, and they are Local Temporary Tables and Global Temporary Tables. Let us see how to work with both Local and Global Temp tables in SQL Server. The following list shows you where we can use the SQL temp tables:

  • When we are working with the complex SQL Server joins.
  • Temp tables are useful to replace the costly cursors. We can use this temp table to store the result set data and manipulate the data from the temp table.
  • We can use this SQL temp table when we are doing a large number of row manipulation in stored procedures. Remember, If we create a temp table inside a stored procedure, it applicable to that SP only. It means you can not call the temp table outside the stored procedure.

Local Temp Table in SQL Server

The name of the SQL Local temporary table starts with the hash (“#”) symbol and stored in the tempdb. SQL Local temporary tables are available only in the current connection. If the user disconnects from current instances or closes the query window, then SQL Local temporary table deletes automatically.

Local Temp Table in SQL Server Syntax

The syntax behind the Sql Server local temporary tables

CREATE TABLE #[Local Temp Table]
(
    Column_Name1 Data_Type(Size) [NULL | NOT NULL],
    Column_Name2 Data_Type(Size) [NULL | NOT NULL],
     …
    Column_NameN Data_Type(Size) [NULL | NOT NULL]
);

Here, Table Name of a SQL local temporary table should start with #. Remember, Please provide a unique name. If you gave the existing table name, it will throw an error

Let us create a SQL local temporary table called LocalTemp.

-- Creating Local Temp Table in SQL Server 
CREATE TABLE #LocalTemp
(
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](255) NULL,
	[LastName] [nvarchar](255) NULL,
	[Occupation] [nvarchar](255) NULL,
	[YearlyIncome] [float] NULL,
	[Sales] [float] NULL
)

We declared 6 Columns in our local temp table. Here, Our first column is ID of Integer data type, and it won’t allow NULL values. We also defined this SQL Server column as Identity starts with 1 and incremented by 1.

Create Temp Table in SQL Server 1

Please refresh the object explorer to see the Newly created Local Temporary table in SQL Server

Create Temp Table in SQL Server 2

Insert Data into Local Temp Table in SQL Server

Let me insert a few random, or sample records into the SQL local temporary table that we created inside the tempdb using the INSERT Statement.

-- Inserting Values into Local SQL Temp Table
INSERT INTO #LocalTemp (
	    [FirstName], [LastName], [Occupation], [YearlyIncome], [Sales])
VALUES ('Tutorial', 'Gateway', 'Education', 10000, 200)
      ,('Imran', 'Khan', 'Skilled Professional', 15900, 100)
      ,('Doe', 'Lara', 'Management', 15000, 60)
      ,('Ramesh', 'Kumar', 'Professional', 65000, 630)

We successfully inserted 4 random records into the #Local Temp table.

Create Temp Table in SQL Server 3

Select Data from Local Temp Table

Let me use the SELECT Statement to select the records present in the local temp table in Sql Server.

-- Selecting Values From Local SQL Temp Table
SELECT [FirstName], 
       [LastName], 
       [Occupation], 
       [YearlyIncome], 
       [Sales] 
FROM #LocalTemp
Create Temp Table in SQL Server 4

Until now, you might wonder why I am writing the Create, Insert, and Select statements in one query window?. Because SQL local temporary tables will last up to a single session, and if you try to call this table from a new query window, then it will throw an error. For example, let me call the #LocalTemp table from a new query window

Create Temp Table in SQL Server 5

As you can see, it is throwing an error stating that, Invalid Object name #LocalTemp. Now, let me close all the existing query windows, and refresh the tempdb from Object Explorer

Create Temp Table in SQL Server 6

From the above screenshot, you can see that it does not contain our #LocalTemp table.

Global Temp Table in SQL Server

The name of the SQL Global temporary table starts with the double hash (“##”) symbol and stored in the tempdb. Global temp tables in SQL Server are like permanent tables, and they are available to all the users in that instance. If all the user disconnects from their session, the SQL global temp tables will automatically delete.

Global Temp Table in SQL Server Syntax

The syntax behind the Global temporary tables in Sql Server

CREATE TABLE ##[Global Temp Table Name]
(
    Column_Name1 Data_Type(Size) [NULL | NOT NULL],
    Column_Name2 Data_Type(Size) [NULL | NOT NULL],
     …
    Column_NameN Data_Type(Size) [NULL | NOT NULL]
);

The SQL global temporary table name should start with ##. Please provide a unique otherwise, it throws an error. Let us create a SQL global temporary table called GlobalTemp.

-- Creating Global Temp Table in SQL Server 
CREATE TABLE ##GlobalTemp
(
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](255) NULL,
	[LastName] [nvarchar](255) NULL,
	[Education] [nvarchar](255) NULL,
	[Occupation] [nvarchar](255) NULL,
	[YearlyIncome] [float] NULL,
	[Sales] [float] NULL
)

We declared 7 Columns for this temp table.

Temp Table in SQL Server 7

See the Newly created Global Temporary table in Sql Server.

Temp Table in SQL Server 8

Insert Data into Global Temp Table in SQL Server

Let me insert a few samples or random records into the global temp table in Sql Server that we created inside the tempdb using the INSERT Statement.

-- Inserting Values into Global SQL Temp Table
INSERT INTO ##GlobalTemp (
	    [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
VALUES ('Tutorial', 'Gateway', 'Masters Degree', 'Teaching', 12000, 200)
      ,('Imran', 'Khan', 'Bachelors', 'Skilled Professional', 13900, 100)
      ,('Doe', 'Lara', 'Degree', 'Management', 25000, 60)
      ,('Ramesh', 'Kumar', 'Bachelors', 'Professional', 35400, 630)
Temp Table in SQL Server 9

Select from Global Temp Table

Here, we successfully inserted 4 random records into the ##GlobalTemp table. Let me use the SELECT Statement to select the records present in that global temp table in Sql Server.

-- Selecting Values From Global SQL Temp Table
SELECT [ID],
       [FirstName], 
       [LastName], 
       [Education], 
       [Occupation],
       [YearlyIncome], 
       [Sales] 
FROM ##GlobalTemp
Temp Table in SQL Server 10

Next, let me call the ##Global Temp table in SQL from a new query window

Temp Table in SQL Server 11

The Temp table is displaying the records, rather than throwing an error. Now, let me close all the existing query windows, and refresh the tempdb from Object Explorer

Create Temp Table in SQL Server 6

Now you can see that there are no temp tables in tempdb database. Please refer to cursors and stored procedures articles.

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW

Copyright © 2021 · All Rights Reserved by Suresh

About Us | Contact Us | Privacy Policy