SQL Server tables: what is the difference between @, # and ##?

前端 未结 6 1136
北恋
北恋 2020-11-29 20:22

In SQL Server, what is the difference between a @ table, a # table and a ## table?

相关标签:
6条回答
  • 2020-11-29 20:35

    if you need a unique global temp table, create your own with a Uniqueidentifier Prefix/Suffix and drop post execution if an if object_id(.... The only drawback is using Dynamic sql and need to drop explicitly.

    0 讨论(0)
  • 2020-11-29 20:41
    CREATE TABLE #t
    

    Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

    CREATE TABLE ##t
    

    Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

    0 讨论(0)
  • 2020-11-29 20:43

    #table refers to a local (visible to only the user who created it) temporary table.

    ##table refers to a global (visible to all users) temporary table.

    @variableName refers to a variable which can hold values depending on its type.

    0 讨论(0)
  • 2020-11-29 20:46

    I would focus on the differences between #table and @table. ##table is a global temporary table and for the record in over 10 years of using SQL Server I have yet to come across a valid use case. I'm sure that some exist but the nature of the object makes it highly unusable IMHO.

    The response to @whiner by @marc_s is absolutely true: it is a prevalent myth that table variables always live in memory. It is actually quite common for a table variable to go to disk and operate just like a temp table.

    Anyway I suggest reading up on the set of differences by following the links pointed out by @Astander. Most of the difference involve limitations on what you can't do with @table variables.

    0 讨论(0)
  • 2020-11-29 20:54

    Have a look at

    • Temporary Tables vs. Table Variables and Their Effect on SQL Server Performance
    • Differences between SQL Server temporary tables and table variables
    • Temp Tables and Table Variables: When To Use What And Why
    0 讨论(0)
  • 2020-11-29 20:54

    # and ## tables are actual tables represented in the temp database. These tables can have indexes and statistics, and can be accessed across sprocs in a session (in the case of a global temp table, it is available across sessions).

    The @table is a table variable.

    For more: http://www.sqlteam.com/article/temporary-tables

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