TSQL笔记7:临时表和表变量

摘要:
CREATETABLE#ProductCostStatistics(ProductIDintNOTNULLPRIMARYKEY,ProductCountintNOTNULL)INSERT#ProductCostStatistics(ProductID,

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).

免责声明:文章转载自《TSQL笔记7:临时表和表变量》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇关于输入框被键盘覆盖及收回键盘的问题谈jdbcTemplate与mybatis下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Django实现支付宝付款和微信支付

支付宝支付和微信支付是当今互联网产品常用的功能,我使用Django Rest Framework实现了网页上支付宝支付和微信支付的一个通用服务,提供rpc接口给其他服务,包括获取支付宝支付页面url的rpc接口、支付宝支付成功异步回调http接口、获取微信支付二维码rpc接口、主动查询微信订单是否支付的rpc接口等。 支付宝网站支付需要蚂蚁金服开放平台账号...

error: variable ‘ParamName’ set but not used [Werror=unusedbutsetvariable]

frameworks/compile/slang/slang_rs_export_foreach.cpp:247:23: error: variable ‘ParamName’ set but not used [-Werror=unused-but-set-variable]cc1plus: all warnings being treated as e...

mysql获取当月数据_MySQL中获取天、周、月等数据

MySQL中获取天、周、月等数据 1.今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 2.昨天 SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) - TO_DAYS( 时间字段名) <= 1 3.近7天 SELECT * FROM 表名 where...

微信APP支付Java后端回调处理

package com.gaoxiao.framework.controller.gaojia;import com.gaoxiao.framework.commonfiles.entity.StatusResult;import com.gaoxiao.framework.commonfiles.utils.PayCommonUtil;import co...

Android 接入支付宝支付实现

接上篇android接入微信支付文章,这篇我们带你来接入支付宝支付服务 简介 首先要说明的是个人感觉接入支付宝比微信简单多了,很轻松的,所以同学们不要紧张~ 当然还是老规矩啦,上来肯定的贴上官网地址,因为我这些服务天天在更新,而我的文章是教大家方法,而让你不是照葫芦画瓢   进入app支付文档有两种方式,一种是直接在下面的开放业务里 还有一种是通...

解读支付宝接口实现步骤

大家想必都有这种困惑——拿到支付宝的接口代码后,尽管里面的程序有注释,接口代码包中也附有开发说明,但还是不知道该如何入手。这不难想象是什么原因,因为自己并不了解这个接口的工作原理是什么?那么这篇文章就是要向大家全面展示关于支付宝接口的所有东西,以便大家能快速上手把接口接入自己的项目中,也能帮助那些已经对支付宝接口有所了解的程序开发者们更了解支付宝的一些通用...