简体   繁体   English

SQL Server 2005临时表

[英]SQL Server 2005 Temporary Tables

In a stored procedure, when is #Temptable created in SQL Server 2005? 在存储过程中,何时在SQL Server 2005中创建#Temptable? When creating the query execution plan or when executing the stored procedure? 在创建查询执行计划时或在执行存储过程时?

if (@x = 1)
    begin
        select 1 as Text into #Temptable
    end
else
    begin
        select 2 as Text into #Temptable
    end

它在执行时创建,在会话结束时删除。

Interesting question. 有趣的问题。

For the type of temporary table you're creating, I think it's when the stored procedure is executed. 对于您要创建的临时表的类型,我认为是在执行存储过程时。 Tables created with the # prefix are accessible to the SQL Server session they're created in. Once the session ends, they're dropped. 使用#前缀创建的表可用于创建它们的SQL Server会话。会话结束后,将其删除。

This url: http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx seems to indicate that temp tables aren't created when query execution plans are created. 该URL: http : //www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx似乎指示在创建查询执行计划时未创建临时表。

虽然可能会在会话结束时自动删除该表,但良好的做法是在完成处理后自行删除该表。

You might also want to consider table variables, whose lifecycle is completely managed for you. 您可能还需要考虑表变量,该表变量的生命周期完全由您管理。

DECLARE @MyTable TABLE (MyPK INT IDENTITY, MyName VARCHAR(100))
INSERT INTO @MyTable ( MyName ) VALUES ( 'Icarus' )
INSERT INTO @MyTable ( MyName ) VALUES ( 'Daedalus' )
SELECT * FROM @MyTable

I almost always use this approach, but it does have disadvantages. 我几乎总是使用这种方法,但是它确实有缺点。 Most notably, you can only use indexes that you can declare within the TABLE() construct, essentially meaning that you're limited to the primary key only -- no using ALTER TABLE. 最值得注意的是,您只能使用可以在TABLE()构造中声明的索引,从本质上讲,您只能使用主键,而不能使用ALTER TABLE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM