views:

1855

answers:

4

In a stored procedure, when is #Temptable created in SQL Server 2005? 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
+2  A: 

It's created when it's executed and dropped when the session ends.

Chris Miller
+1  A: 

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.

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.

Scott A. Lawrence
A: 

Whilst it may be automatically dropped at the end of a session, it is good practice to drop the table yourself when you're done with it.

Scott Bennett-McLeish
+1  A: 

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.

Chris Wuestefeld