T-SQL笔记7:临时表和表变量

本章摘要:

1:临时表

2:表变量

3:两者的取舍

1:临时表

Temporary tables are defined just like regular tables, only they are automatically stored in the tempdb database (no matter which database context you create them in).

There are two different temporary table types: globaland local. Local temporary tables are prefixed with a single # sign, and global temporary tables with a double ## sign.

Local temporary tables are dropped by using the DROP statement or are automatically removed from memory when the user connection is closed.

Global temporary tables are removed fromSQL Server if explicitly dropped by DROP TABLE. They are also automatically removed after the connection that created it exits and the global temporary table is no longer referenced by other connections. As an a side,  I rarely see global temporary tables used in the field.

1.1:Using aTemporary Table for Multiple Lookups Within aBatch

In this example, I’ll demonstrate creating a local temporary table that is then referenced multiple times in a batch of queries. This technique can be helpful if the query used to generate the lookup values takes several seconds to execute. Rather then execute the SELECT query multiple times, we can query the pre-aggregated temp table instead:

CREATE TABLE #ProductCostStatistics
( ProductID int NOT NULL PRIMARY KEY,
AvgStandardCost money NOT NULL,
ProductCount int NOT NULL)
INSERT #ProductCostStatistics
(ProductID, AvgStandardCost, ProductCount)
SELECT ProductID,
AVG(StandardCost) AvgStandardCost,
COUNT(ProductID) Rowcnt
FROM Production.ProductCostHistory
GROUP BY ProductID
GO
SELECT TOP 3 *
FROM #ProductCostStatistics
ORDER BY AvgStandardCost ASC
SELECT TOP 3 *
FROM #ProductCostStatistics
ORDER BY AvgStandardCost DESC
SELECT AVG(AvgStandardCost) Average_of_AvgStandardCost
FROM #ProductCostStatistics
DROP TABLE #ProductCostStatistics 

How It Works
    In this recipe, a temporary table called #ProductCostStatisticswas created. The table had rows inserted into it like a regular table, and then the temporary table was queried three times (again, just like aregular table), and then dropped. The table was created and queried with the same syntax as aregular table, only the temporary table name was prefixed with a # sign. In situations where the initial population query execution time takes too long to execute, this is one technique to consider.

2:表变量

Microsoft recommends table variables as a replacement of temporary tables when the data set is not very large (which is avague instruction—in the end it is up to you to test which table types work best in your environment). A table variable is a data type that can be used within a Transact-SQL batch, stored procedure, or function—and is created and defined similarly to a table, only with a strictly defined lifetime scope.
    Unlike regular tables or temporary tables, table variables can’t have indexes or FOREIGN KEY constraints added to them. Table variables do allow some constraints to be used in the table definition (PRIMARY KEY, UNIQUE, CHECK).

2.1:Creating aTable Variable to Hold aTemporary Result Set

The syntax to creating a table variable is similar to creating atable, only the DECLARE keyword is used and the table name is prefixed with an @ symbol:

DECLARE @TableName TABLE
(column_name <data_type> [ NULL | NOT NULL ] [ ,...n ]  )

In this example, a table variable is used in a similar fashion to the temporary table of the previous recipe. This example demonstrates how the implementation differs (including how you don’t explicitly DROPthe table):

DECLARE @ProductCostStatistics TABLE
( ProductID int NOT NULL PRIMARY KEY,
AvgStandardCost money NOT NULL,
ProductCount int NOT NULL)
INSERT @ProductCostStatistics
(ProductID, AvgStandardCost, ProductCount)
SELECT ProductID,
AVG(StandardCost) AvgStandardCost,
COUNT(ProductID) Rowcnt
FROM Production.ProductCostHistory
GROUP BY ProductID
SELECT TOP 3 *
FROM @ProductCostStatistics
ORDER BY ProductCount

How It Works
    This recipe used a table variable in much the same way as the previous recipe did with temporary tables. There are important distinctions between the two recipes however.

First, this time a table variable was defined using DECLARE @Tablename TABLE instead of CREATE TABLE. Secondly, unlike the temporary table recipe, there isn’t a GO after each statement, as temporary tables can only be scoped within the batch, procedure, or function.  In the next part of the recipe, you’ll use inserts and selects from the table variable as you would a regular table, only this time using the @tablenameformat:

INSERT @ProductCostStatistics
...
SELECT TOP 3 *
FROM @ProductCostStatistics
...

No DROP TABLE was necessary at the end of the example, as the table variable is eliminated from memory after the end of the batch/procedure/function execution.

3:两者的取舍

Reasons to use table variables include:
    * Well scoped. The lifetime of the table variable only lasts for the duration of the batch, function, or stored procedure.
    * Shorter locking periods (because of the tighter scope).
    * Less recompilation when used in stored procedures.
    There are drawbacks to using table variables though. Table variable performance suffers when the result set becomes too large (defined by your hardware, database design, and query). When encountering performance issues, be sure to test all alternative solutions and don’t necessarily assume that one option (temporary tables) is less desirable than others (table variables).

T-SQL笔记7:临时表和表变量相关推荐

  1. SQL Server中临时表与表变量的区别

    我们在数据库中使用表的时候,经常会遇到两种使用表的方法,分别就是使用临时表及表变量.在实际使用的时候,我们如何灵活的在存储过程中运用它们,虽然它们实现的功能基本上是一样的,可如何在一个存储过程中有时候 ...

  2. [导入]SQL中的临时表和表变量

    我们经常使用临时表和表变量,那现在我们就对临时表和表变量进行一下讨论. 临时表 局部临时表 全局临时表 表变量 临时表 临 时表存储在TempDB数据库中,所有的使用此SQL Server 实例的用户 ...

  3. SQL Server--[转]SQL Server中临时表与表变量的区别

    http://blog.csdn.net/skyremember/archive/2009/03/05/3960687.aspx 我们在数据库中使用表的时候,经常会遇到两种使用表的方法,分别就是使用临 ...

  4. php sql server临时表,SQLServer中临时表与表变量的区别分析

    在实际使用的时候,我们如何灵活的在存储过程中运用它们,虽然它们实现的功能基本上是一样的,可如何在一个存储过程中有时候去使用临时表而不使用表变量,有时候去使用表变量而不使用临时表呢? 临时表 临时表与永 ...

  5. sql 表变量 临时表_SQL表变量概述

    sql 表变量 临时表 This article explores the SQL Table variables and their usage using different examples. ...

  6. sql语句用变量替换表名_使用内存优化表替换SQL临时表和表变量

    sql语句用变量替换表名 TempDB usage can be considered as a performance bottleneck for workloads that use SQL t ...

  7. 存储过程中引用的常规表,临时表以及表变量是否会导致存储过程的重编译

    在存储过程中,经常要引用一些表来存储一些中间数据,用完即删.对于这个中间表,用常规表,临时表或者表变量有什么区别呢? 下面我们看一下这三种中间表是否会造成执行计划的重编译. 首先打开sql serve ...

  8. SqlServer 中的临时表与表变量

    我们在数据库中使用表的时候,经常会遇到两种使用表的方法,分别就是使用临时表及表变量.在实际使用的时候,我们如何灵活的在存储过程中运用它们,虽然它们实现的功能基本上是一样的,可如何在一个存储过程中有时候 ...

  9. 临时表与表变量深入探究

    临时表或表变量我们一般用来充当中间结果集,很多时候都在用,但真正了解他们之间的区别的人还是很少的,网上流传的说法也不甚统一,所以今天我就做一个实验,让我们看看临时表和表变量的区别,以及他们各自的用途. ...

最新文章

  1. 开源框架完美组合之Spring.NET + NHibernate + ASP.NET MVC + jQuery + easyUI 中英文双语言小型企业网站Demo项目分析
  2. 压缩信息立方体和集合技术内幕
  3. 逻辑漏洞——业务逻辑问题
  4. java多线程原子操作_Java 多线程 - 原子操作CAS
  5. STM32F103+CubeMX-Keil上移植RTX5实时系统
  6. linux下面的j2sdk的安装和配置过程
  7. dos批处理命令注释_如何在批处理文件MS-DOS中写注释块?
  8. HTML期末学生大作业 响应式动漫网页作业 html+css+javascript (1)
  9. 微云解析直链php源码,微云分享文件直链解析源码
  10. 福建将乐窑文物首次系统对外展示 133件完整器亮相京城
  11. 鸿蒙第三代手机,原创 荣耀Magic 3最新确认,鸿蒙系统+双6400万,最期待的荣耀来了...
  12. 共享单车泡沫破灭,自行车产业链的每个环节都被波及
  13. 软件的基本是要处理好”算法“及其基础(一)流-字-字符(包括某个数字、字母、符号和某个汉字等)-字符串-字节动态数组-字节-整数之间的转化关系和算法
  14. 域策略(2)——设置统一桌面背景
  15. Windows 在目录中搜索哪个文件中有指定字符串
  16. (Nginx出现403 forbidden)nginx权限问题failed(13:Permission denied)
  17. Android 下载 自动安装 解析错误,studio下载APK到手机提示解析错误解决方法
  18. 小菜鸟初次接触JBoss应用服务器
  19. 50Projects50Days--RotatingNavgation
  20. 腾讯云服务器安装什么系统,腾讯云服务器操作系统TencentOS安装与体验

热门文章

  1. 试验thrift做后端rpc,nginx做web服务器, python后端php前端
  2. 优化篇-“移动端”图片上传架构的变迁
  3. UVA455 Periodic Strings
  4. Playframework项目启动后自动停止问题记录
  5. 基于webview的选择滑动控件(PC和wap版)
  6. Windows Home Server 常见问题
  7. Egret之属性绑定
  8. php中三元运算符用法
  9. Android应用程序插件化研究之DexClassLoader
  10. struts2 + ajax 用户名登录验证(struts2+spring+ibatis)