Home Forums SQL Server 2005 Development Can a temporary table created with an execute statement survive that statement? RE: Can a temporary table created with an execute statement survive that statement?

  • kent waldrop (3/10/2008)


    Jeff:

    What are the circumstances for that? When I run the following query it get the commented results:

    use tempdb

    go

    select name as before from sysobjects where type = 'U'

    exec ( 'create table #what(a int) select name as during from sysobjects where type = ''U'' ')

    select name as after from sysobjects where type = 'U' order by name

    /* -------- Sample Output: --------

    before

    ------------------------

    during

    --------------------------------------------------------------------------------------------------------------------------------

    #what_______________________________________________________________________________________________________________000000000005

    after

    ------------------------

    */

    Because, by definition, temporary tables are scope sensitive by session and by proc. If you create it in the outer proc, sub-procs are in the same scope. If you create it in a sub-proc (EXEC qualifies as a subproc), then the temp table will not be available to the outer proc because there's a scope change. See Books Online for more information about scope sensitivety of temp tables...

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)