Temporary tables are created in tempdb.  The name "temporary" is slightly misleading, for even though the tables are instantiated in tempdb and backed by physical disk and are even logged into the transaction log.  They act like regular tables in that you can query their data via SELECT queries and modify their data via UPDATE, INSERT, and DELETE statements.  If created inside a stored procedure they are destroyed upon completion of the stored procedure.  Furthermore, the scope of any particular temporary table is the session in which it is created; meaning it is only visible to the current user.  Multiple users could create a temp table named #TableX and any queries run simultaneously would not affect one another - they would remain autonomous transactions and the tables would remain autonomous objects.  You may notice that my sample temporary table name started with a "#" sign.  This is the identifier for SQL Server that it is dealing with a temporary table.

There are two types temporary table. One is session scope, another one is global scope.

1. Session scope temporary table

the identifier of a session scope temporary table must be start with '#', below is an example.Sesson scope temporary table can have clustered and nonclutered index.It only visiable to current session, mutiple session will have a differenttamporary table instance. It will auto destoryed at the end of the session. If it defined in a procedure, then it will be destoryed at the end of the procedure.

create table #table1(

                               column1 int primary key,

                               column2 int,

                               column3 int,

                               column4 int

                              );

create noclustered index idx_table1_column2 on #table1(column2);

2. Global scope temporary table

the identifier of a global scope temporary table must be start with '##', below is an example.

Global scope temporary table can have clustered and nonclutered index.It is visiable to all the session,

it will be destroyed when restart SQLServer.

create table ##table2(

                               column1 int primary key,

                               column2 int,

                               column3 int,

                               column4 int

                              );

create noclustered index idx_table2_column2 on ##table2 (column2);

3. Table variable in T-SQL

In a procedue we can have a table variable, below is a example for how to create it. The table variable can have single column primary key or composit primary key of several columns. We can have clustered index on the primary key, but we can have nonclusted index.Below are two example about how to define table variable.

declare @table3  table (

                               column1 int primary key,

                               column2 int,

                               column3 int,

                               column4 int

                               );
declare @table4  table (

                               column1 int,

                               column2 int,

                               column3 int,

                               column4 int

                               primary key(column1,column2)

                               );

The table variable exactly is also instantiated in the tempdb. Some one thought it was a memory table,but that's not true.

Below is an experiment to show it is stored in tempdb.

/* Check the difference between Temp Table and Memory Tables */
-- Get Current Session ID
SELECT @@SPID AS Current_SessionID
-- Check the space usage in page files
SELECT user_objects_alloc_page_count
FROM sys.dm_db_session_space_usage
WHERE session_id = (SELECT @@SPID )
GO
-- Create Temp Table and insert three thousand rows
CREATE TABLE #TempTable (Col1 INT)
INSERT INTO #TempTable (Col1)
SELECT TOP 3000 ROW_NUMBER() OVER(ORDER BY a.name)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
GO
-- Check the space usage in page files
SELECT user_objects_alloc_page_count
FROM sys.dm_db_session_space_usage
WHERE session_id = (SELECT @@SPID )
GO
-- Create Table Variable and insert three thousand rows
DECLARE @temp TABLE(Col1 INT)
INSERT INTO @temp (Col1)
SELECT TOP 3000 ROW_NUMBER() OVER(ORDER BY a.name)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
GO
-- Check the space usage in page files
SELECT user_objects_alloc_page_count
FROM sys.dm_db_session_space_usage
WHERE session_id = (SELECT @@SPID )
GO
-- Clean up
DROP TABLE #TempTable
GO

Temporary table:

  • Table variables can have Clustered and Non-Clustered Indexes
  • You can have constraints
  • You can create default values on columns
  • Statistics can be created against table variables

Table variable have certain clear limitations: 

  • Table variables can not have Non-Clustered Indexes,but it can have clustered index
  • You can not create constraints in table variables
  • You can not create default values on table variable columns
  • Statistics can not be created against table variables

Common for temporary table and table variable

  • Instantiated in tempdb
  • Clustered indexes can be created on table variables and temporary tables
  • Both are logged in the transaction log
  • Just as with temp and regular tables, users can perform all Data Modification Language (DML) queries against a table variable:  SELECT, INSERT, UPDATE, and DELETE.

SQLServer temporary table and table variable的更多相关文章

  1. sqlserver不能直接create table as select

    sqlserver不能直接create table as select 在sqlserver 下想复制一张表的,想到oracle下直接create table xxx as select * from ...

  2. InnoDB INFORMATION_SCHEMA Temporary Table Info Table

    InnoDB INFORMATION_SCHEMA Temporary Table Info Table INNODB_TEMP_TABLE_INFO提供有关InnoDB实例中当前活动的用户创建的In ...

  3. 表优化 altering table OPTIMIZE TABLE `sta_addr_copy`

    表优化 altering table OPTIMIZE TABLE `sta_addr_copy` [总结] 1.实际测试的结果是,在state sqlaltering table OPTIMIZE ...

  4. mysqldump:Couldn't execute 'show create table `tablename`': Table tablename' doesn't exist (1146)

    遇到了一个错误mysqldump: Couldn't execute 'show create table `CONCURRENCY_ERRORS`': Table INVOICE_OLD.CONCU ...

  5. ORA-01747: user.table.column, table.column 或列说明无效

    Oracle.DataAccess.Client.OracleException ORA-01747: user.table.column, table.column 或列说明无效 原因1: 查了一下 ...

  6. Oracle10g 回收站及彻底删除table : drop table xx purge

    drop后的表被放在回收站(user_recyclebin)里,而不是直接删除掉.这样,回收站里的表信息就可以被恢复,或彻底清除. 1.通过查询回收站user_recyclebin获取被删除的表信息, ...

  7. user.table.column, table.column 或列说明无效

    Oracle统计采用别名出错(user.table.column, table.column 或列说明无效) >>>>>>>>>>>& ...

  8. lua中打印所以类型功能实现table嵌套table

    lua中打印所以类型功能实现 本人測试 number.string.bool.nil.table嵌套table.userdata没问题 共享一下有什么问题请拍砖 代码例如以下 cclog = func ...

  9. 使用vue的v-for生成table , 给table加上序号

    现在有一个使用mybatis的分页插件生成的table,table中数据是通过vue获得的 , 前台显示使用<tr v-for="item in items"> 后台v ...

随机推荐

  1. 外部调用JS文件时出现中文乱码的解决办法

    若测试网页的编码格式为:gb2312,而调用外部JS文件时出现了乱码(前提是JS文件无错误),则将调用的外部JS文件用记事本打开,然后再保存成编码格式为UTF-8的JS文件即可. 若测试网页的编码格式 ...

  2. virt-manage图形界面键盘错位问题

    键盘错乱问题: 启动引导问题:

  3. opengl画圆

    通过这个例子可以更加深刻的了解割圆术的原理,明白如何的化曲为直,且看代码: #include <windows.h> //#include <GLUT/glut.h> #inc ...

  4. Jersey MVC

    Jersey是JAX-RS(JavaAPI for RESTful Service)标准的一个实现,用于开发RESTful Web Application.可以参考JAX-RS的介绍(http://w ...

  5. mysql join表连接

    1.表连接,就是将两个表合并起来,被合并的表的记录要通过中间字段,一一匹配起来左边的表的记录,形成一张临时的合并的表,并且每条记录的值都是两张表一一准确对应的 实例 尝试以下实例: root@host ...

  6. thinkPHP实现瀑布流的方法

    thinkPHP实现瀑布流的方法 文章TAG:thinkphp 瀑布流 时间:2014-11-29来源:www.aspku.com 作者:源码库 文章热度: 131 ℃ 过期已备案域名,注册就能用!终 ...

  7. xenserver+starwind架构布署

    主机 CPU 和主板均需支持 INTER-VT/ AMD-VT ,主板默认可能没开  进BISO开启  下载最新的 xenserver ,授权注册一下 轻松得到授权文件 (鄙视一下VMWARE,看人家 ...

  8. MVC两个必懂核心

    ASP.NET MVC由以下两个核心组成部分构成: 一个名为UrlRoutingModule的自定义HttpModule,用来解析Controller与Action名称: 一个名为MvcHandler ...

  9. DropzoneJS 使用指南

    原文链接http://segmentfault.com/a/1190000004045240 官方文档: http://www.dropzonejs.com/ Github: https://gith ...

  10. kafka监控系统

    Metrics-Java版的指标度量工具之一 Metrics-Java版的指标度量工具之二 JAVA Metrics 度量工具使用介绍1 JAVA Metrics度量工具 - Metrics Core ...