我有一个疑问,为什么我们应该使用临时表临时表中有什么特别的东西,我们应该在哪里使用临时表。你能解释一下我或任何参考谢谢。
3 回答
在编写 T-SQL 代码时,您通常需要一个表来在执行该代码时临时存储数据。您有四个表选项:普通表、本地临时表、全局临时表和表变量。四个表选项中的每一个都有自己的目的和用途,并且每个都有其优点和问题:
* Normal tables are exactly that, physical tables defined in your database.
* Local temporary tables are temporary tables that are available only to the session that created them. These tables are automatically destroyed at the termination of the procedure or session that created them.
* Global temporary tables are temporary tables that are available to all sessions and all users. They are dropped automatically when the last session using the temporary table has completed. Both local temporary tables and global temporary tables are physical tables created within the tempdb database.
* Table variables are stored within memory but are laid out like a table. Table variables are partially stored on disk and partially stored in memory. It's a common misconception that table variables are stored only in memory. Because they are partially stored in memory, the access time for a table variable can be faster than the time it takes to access a temporary table.
使用哪一个:
* If you have less than 100 rows generally use a table variable. Otherwise use a temporary table. This is because SQL Server won't create statistics on table variables.
* If you need to create indexes on it then you must use a temporary table.
* When using temporary tables always create them and create any indexes and then use them. This will help reduce recompilations. The impact of this is reduced starting in SQL Server 2005 but it's still a good idea.
临时表有很多用途。它们在处理复杂查询中的数据时非常有用。您的问题含糊不清,并没有真正的答案,但我正在链接到一些临时表文档。
它们具有表的大部分相同功能,包括约束和索引。它们可以是全局的或仅限于当前范围。它们也可能效率低下,因此请一如既往地谨慎。
http://www.sqlservercentral.com/articles/T-SQL/temptablesinsqlserver/1279/
http://msdn.microsoft.com/en-us/library/aa258255%28SQL.80%29.aspx
临时表可以在运行时创建,可以做一张普通表可以做的各种操作。但是,根据表类型,范围是有限的。这些表是在 tempdb 数据库中创建的。
SQL Server 根据表的行为和范围提供两种类型的临时表。这些都是:
•<strong>本地温度表
•<strong>全球温度表
本地临时表 本地临时表只对用户当前连接可用;当用户与实例断开连接时,它们会自动删除。本地临时表名以井号(“#”)开头。全局临时表 全局临时表名称以双哈希 ( "##" ) 开头。一旦这个表由一个连接创建,就像一个永久表一样,任何用户都可以通过任何连接使用它。只有在关闭所有连接后才能将其删除。
何时使用临时表?
• 当我们在存储过程中进行大量行操作时。•这对替换光标很有用。我们可以将结果集数据存储到临时表中,然后我们可以从那里操作数据。•<strong>当我们进行复杂的连接操作时。
使用临时表之前要记住的要点 -
• 在 SQL Server 的 tempdb 上创建的临时表。这是一个单独的数据库。因此,这是额外的开销,可能会导致性能问题。• 行数和列数需要尽可能少。•完成工作后需要删除表格。
替代方法:表变量-
临时表的替代方案是表变量,它可以执行我们可以在临时表中执行的各种操作。下面是使用 Table 变量的语法。
何时在临时表上使用表变量 -
表变量对于较少的数据总是有用的。如果结果集返回大量记录,我们需要去临时表。