SQL Server 2005 and temporary table scope

前端 未结 3 1369
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 05:21

I\'ve read around the subject of temporary tables and scope and all the answers i\'ve seen don\'t seem to talk about one of my concerns.

I understand that a local te

相关标签:
3条回答
  • 2020-12-01 05:38

    Local temporary tables (start with #) are limited to your session; other sessions, even from the same user/connection string, can't see them. The rules for the lifetime depend on whether the local temporary table was created in a stored procedure:

    • A local temporary table that is created in a stored procedure is dropped when the procedure ends; other stored procedures, or the calling process, can't see them.
    • Other local temporary tables are dropped when the session ends.

    Global temporary tables (start with ##) are shared between sessions. They are dropped when:

    • The session that created them ends
    • AND no other session is referring to them

    This command can be handy to see which temporary tables exist:

    select TABLE_NAME from tempdb.information_schema.tables 
    

    And this is handy to drop temporary tables if you're not sure they exist:

    if object_id('tempdb..#SoTest') is not null drop table #SoTest
    

    See this MSDN article for more information.

    0 讨论(0)
  • 2020-12-01 05:43

    You might also think about using table variables. They have a very well-defined scope, and they are sometimes faster than their temporary table counterparts. The only problem with table variables is that they cannot be indexed, so some performance could be lost despite their nature. Check here for some more information on the subject.

    0 讨论(0)
  • 2020-12-01 05:52

    The temporary table will be accesible to the instance of the procedure that creates it

    The following script

    Exec ('Select 1 as col Into #Temp Select * From #Temp')
    Exec ('Select 2 as col Into #Temp Select * From #Temp')
    

    Returns

    Col
    1
    
    Col
    2
    

    Not

    Col
    1
    2
    

    Or an error because the table already exists.

    The temporary table will also be accesible by any 'child' procedures that the initial procedure runs as well.

    0 讨论(0)
提交回复
热议问题