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

简介: T-SQL笔记7:临时表和表变量 本章摘要: 1:临时表 2:表变量 3:两者的取舍   1:临时表     Temporary tables are defined just like regular tables, only they are automatically stored in ...

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

Creative Commons License本文基于 Creative Commons Attribution 2.5 China Mainland License发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名 http://www.cnblogs.com/luminji(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。
目录
相关文章
|
6月前
|
SQL 存储 Oracle
Oracle的PL/SQL定义变量和常量:数据的稳定与灵动
【4月更文挑战第19天】在Oracle PL/SQL中,变量和常量扮演着数据存储的关键角色。变量是可变的“魔术盒”,用于存储程序运行时的动态数据,通过`DECLARE`定义,可在循环和条件判断中体现其灵活性。常量则是不可变的“固定牌”,一旦设定值便保持不变,用`CONSTANT`声明,提供程序稳定性和易维护性。通过 `%TYPE`、`NOT NULL`等特性,可以更高效地管理和控制变量与常量,提升代码质量。善用两者,能优化PL/SQL程序的结构和性能。
|
6月前
|
SQL 关系型数据库 MySQL
《SQL必知必会》个人笔记(一)
《SQL必知必会》个人笔记(一)
61 0
|
6月前
|
SQL 关系型数据库 MySQL
【MySQL实战笔记】02.一条SQL更新语句是如何执行的-1
【4月更文挑战第4天】SQL更新语句执行涉及查询和日志模块,主要为`redo log`和`binlog`。`redo log`先写日志再写磁盘,保证`crash-safe`;`binlog`记录逻辑日志,支持所有引擎,且追加写入。执行过程分为执行器查找数据、更新内存和`redo log`(prepare状态)、写入`binlog`、提交事务(`redo log`转commit)。两阶段提交确保日志逻辑一致,支持数据库恢复至任意时间点。
52 0
|
4月前
|
SQL 运维 分布式计算
DataWorks产品使用合集之ODPPS中如何使用SQL查询从表中获取值并将其赋值给临时变量以供后续使用
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
|
5月前
|
SQL 存储 关系型数据库
技术笔记:MYSQL常用基本SQL语句总结
技术笔记:MYSQL常用基本SQL语句总结
37 0
|
5月前
|
SQL 存储 分布式计算
MaxCompute产品使用问题之odps sql如何定义变量
MaxCompute作为一款全面的大数据处理平台,广泛应用于各类大数据分析、数据挖掘、BI及机器学习场景。掌握其核心功能、熟练操作流程、遵循最佳实践,可以帮助用户高效、安全地管理和利用海量数据。以下是一个关于MaxCompute产品使用的合集,涵盖了其核心功能、应用场景、操作流程以及最佳实践等内容。
157 0
|
5月前
|
SQL 缓存 Oracle
SQL调优之绑定变量用法简介
SQL调优之绑定变量用法简介
|
6月前
|
SQL 关系型数据库 MySQL
【MySQL系列笔记】常用SQL
常用SQL分为三种类型,分别为DDL,DML和DQL;这三种类型的SQL语句分别用于管理数据库结构、操作数据、以及查询数据,是数据库操作中最常用的语句类型。 在后面学习的多表联查中,SQL是分析业务后业务后能否实现的基础,以及后面如何书写动态SQL,以及完成级联查询的关键。
247 6
|
6月前
|
SQL 存储 关系型数据库
【MySQL系列笔记】SQL优化
SQL优化是通过调整数据库查询、索引、表结构和配置参数等方式,提高SQL查询性能和效率的过程。它旨在减少查询执行时间、减少系统资源消耗,从而提升数据库系统整体性能。优化方法包括索引优化、查询重写、表分区、适当选择和调整数据库引擎等。
289 3
|
6月前
|
SQL 存储 Oracle
《SQL必知必会》个人笔记
《SQL必知必会》个人笔记
41 1