Difference between #temptable and ##TempTable?

后端 未结 6 1231
臣服心动
臣服心动 2020-12-02 16:16

What is the difference between #temptable and ##TempTable in SQL Server?

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 17:00

    #TempTables aren't just local to the User, or connection. They are local to the process that created them and any processes that the creating process spawns. For example if I have the following:

    Declare @strDynamicSQL as varchar(8000)
    
    Set @strDynamicSQL = 'Select GetDate() As TheDate Into #TheDateTable'
    Execute(@strDynamicSQL)
    
    Select *
    From #TheDateTable
    

    I get the following error:

    Msg 208, Level 16, State 0, Line 7 Invalid object name '#TheDateTable'.

    But if I do:

    Declare @strDynamicSQL as varchar(8000)
    
    Create Table #TheDateTable (
        TheDate     DateTime
    )
    
    Set @strDynamicSQL = 'Insert Into #TheDateTable Select GetDate() As TheDate'
    Execute(@strDynamicSQL)
    
    Select *
    From #TheDateTable
    

    I get no errors.

    In the first example the Execute statement happens in a spawned process. Since the table is created in that process when it returns that process goes away. And with the process the table is "bye-bye".

    In the second example the table is created by the top level process. It's then interacted with in the spawned process. The table is available to the process that it was created in and any process it spawns.

    ##tables break this. The process a ## table is created in will be the controlling process. The table will not get flagged for removal if this process is still alive even if there are no tasks against that process. Once the process that the ## table was created in goes away, the table is tagged for removal when the last task is executed against it.

    Here is a simple way to see it. # tables are available only in the scope of the process that it was created in. ## are available in the same way as any other table except that the existence comes and goes with the process it was created in.

提交回复
热议问题