41

How to create a temp table similarly to creating a normal table?

Example:

CREATE TABLE table_name 
(
    column1 datatype,
    column2 datatype,
    column3 datatype,
     ....
 );
Jim G.
  • 15,141
  • 22
  • 103
  • 166
Liam neesan
  • 2,282
  • 6
  • 33
  • 72

2 Answers2

67

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

CarenRose
  • 1,266
  • 1
  • 12
  • 24
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
55

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz
Mark Kremers
  • 1,669
  • 12
  • 20
  • 4
    The usage of *session* is not correct... A `@table` is - like any variable - bound to one job. It will disappear with a `GO` and a called SP or function does not know it. A `#table` will live within one session, even in a called SP or function, while a `##table` can be reached from different sessions. – Shnugo Mar 26 '17 at 09:42
  • 2
    Also, a table variable is not a temporary table. Read Martin Smith's [post on DBO.StackExchange about it](http://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386) for details. – Zohar Peled Mar 26 '17 at 09:57
  • Table variables can often lead to poor execution plans due to their lack of indexes and statistics. They are scoped to the current **batch**, not "job" or session. While they have their uses, they are often not the best choice vs. a temp table. – alroc Mar 26 '17 at 11:42
  • A table variable is a temporary table, not a table created within the tempdb. However, even a @ table uses the tempdb (see https://blog.sqlauthority.com/2009/12/15/sql-server-difference-temptable-and-table-variable-temptable-in-memory-a-myth/) – Mark Kremers Mar 26 '17 at 13:05
  • A table variable is not the same as a temporary table. They are quite different. Also, a global temporary table (`##`) can be accessed within different sessions and if I remember correctly, also by different logins. – ATC Jan 08 '19 at 14:04