如何在 SQL Server 中使用 Create 语句创建临时表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43026755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create temp table using Create statement in SQL Server?
提问by Liam neesan
How to create a temp table similarly to creating a normal table?
如何创建一个类似于创建普通表的临时表?
Example:
例子:
CREATE TABLE table_name
(
column1 datatype,
column2 datatype,
column3 datatype,
....
);
回答by Zohar Peled
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.
临时表名以#
or开头##
- 第一个是本地临时表,最后一个是全局临时表。
Hereis one of many articles describing the differences between them.
这是描述它们之间差异的许多文章之一。
回答by Mark Kremers
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.
一个临时表可以有3种,#
最常用的。这是一个仅存在于当前会话中的临时表。与 this 等效的是@
,声明的表变量。这具有较少的“功能”(如索引等),并且也仅用于当前会话。的##
是一个是一样的#
,但是,范围更广,因此您可以在同一会话中使用它,其他的存储过程中。
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