What's the difference between a temp table and table variable in SQL Server?

后端 未结 12 1121
抹茶落季
抹茶落季 2020-11-22 05:03

In SQL Server 2005, we can create temp tables one of two ways:

declare @tmp table (Col1 int, Col2 int);

or

create table #tm         


        
相关标签:
12条回答
  • 2020-11-22 05:40
    1. Temp table: A Temp table is easy to create and back up data.

      Table variable: But the table variable involves the effort when we usually create the normal tables.

    2. Temp table: Temp table result can be used by multiple users.

      Table variable: But the table variable can be used by the current user only. 

    3. Temp table: Temp table will be stored in the tempdb. It will make network traffic. When we have large data in the temp table then it has to work across the database. A Performance issue will exist.

      Table variable: But a table variable will store in the physical memory for some of the data, then later when the size increases it will be moved to the tempdb.

    4. Temp table: Temp table can do all the DDL operations. It allows creating the indexes, dropping, altering, etc..,

      Table variable: Whereas table variable won't allow doing the DDL operations. But the table variable allows us to create the clustered index only.

    5. Temp table: Temp table can be used for the current session or global. So that a multiple user session can utilize the results in the table.

      Table variable: But the table variable can be used up to that program. (Stored procedure)

    6. Temp table: Temp variable cannot use the transactions. When we do the DML operations with the temp table then it can be rollback or commit the transactions.

      Table variable: But we cannot do it for table variable.

    7. Temp table: Functions cannot use the temp variable. More over we cannot do the DML operation in the functions .

      Table variable: But the function allows us to use the table variable. But using the table variable we can do that.

    8. Temp table: The stored procedure will do the recompilation (can't use same execution plan) when we use the temp variable for every sub sequent calls.

      Table variable: Whereas the table variable won't do like that.

    0 讨论(0)
  • 2020-11-22 05:44

    There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.

    As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)

    Some points to consider when choosing between them:

    • Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.

    • Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) SQL 2014 has non-unique indexes too.

    • Table variables don't participate in transactions and SELECTs are implicitly with NOLOCK. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!

    • Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.

    • You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.

    • You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).

    • Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.

    • Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (ref). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.

    • Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.

    Some further reading:

    • Martin Smith's great answer on dba.stackexchange.com

    • MSDN FAQ on difference between the two: https://support.microsoft.com/en-gb/kb/305977

    • MDSN blog article: https://docs.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table

    • Article: https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables

    • Unexpected behaviors and performance implications of temp tables and temp variables: Paul White on SQLblog.com

    0 讨论(0)
  • 2020-11-22 05:45

    For all of you who believe the myth that temp variables are in memory only

    First, the table variable is NOT necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.

    Read the article here: TempDB:: Table variable vs local temporary table

    0 讨论(0)
  • 2020-11-22 05:46

    Quote taken from; Professional SQL Server 2012 Internals and Troubleshooting

    Statistics The major difference between temp tables and table variables is that statistics are not created on table variables. This has two major consequences, the fi rst of which is that the Query Optimizer uses a fi xed estimation for the number of rows in a table variable irrespective of the data it contains. Moreover, adding or removing data doesn’t change the estimation.

    Indexes You can’t create indexes on table variables although you can create constraints. This means that by creating primary keys or unique constraints, you can have indexes (as these are created to support constraints) on table variables. Even if you have constraints, and therefore indexes that will have statistics, the indexes will not be used when the query is compiled because they won’t exist at compile time, nor will they cause recompilations.

    Schema Modifications Schema modifications are possible on temporary tables but not on table variables. Although schema modifi cations are possible on temporary tables, avoid using them because they cause recompilations of statements that use the tables.

    TABLE VARIABLES ARE NOT CREATED IN MEMORY

    There is a common misconception that table variables are in-memory structures and as such will perform quicker than temporary tables. Thanks to a DMV called sys . dm _ db _ session _ space _ usage , which shows tempdb usage by session, you can prove that’s not the case. After restarting SQL Server to clear the DMV, run the following script to confi rm that your session _ id returns 0 for user _ objects _ alloc _ page _ count :

    SELECT session_id,
    database_id,
    user_objects_alloc_page_count
    FROM sys.dm_db_session_space_usage
    WHERE session_id > 50 ;
    

    Now you can check how much space a temporary table uses by running the following script to create a temporary table with one column and populate it with one row:

    CREATE TABLE #TempTable ( ID INT ) ;
    INSERT INTO #TempTable ( ID )
    VALUES ( 1 ) ;
    GO
    SELECT session_id,
    database_id,
    user_objects_alloc_page_count
    FROM sys.dm_db_session_space_usage
    WHERE session_id > 50 ;
    

    The results on my server indicate that the table was allocated one page in tempdb. Now run the same script but use a table variable this time:

    DECLARE @TempTable TABLE ( ID INT ) ;
    INSERT INTO @TempTable ( ID )
    VALUES ( 1 ) ;
    GO
    SELECT session_id,
    database_id,
    user_objects_alloc_page_count
    FROM sys.dm_db_session_space_usage
    WHERE session_id > 50 ;
    

    Which one to Use?

    Whether or not you use temporary tables or table variables should be decided by thorough testing, but it’s best to lean towards temporary tables as the default because there are far fewer things that can go wrong.

    I’ve seen customers develop code using table variables because they were dealing with a small amount of rows, and it was quicker than a temporary table, but a few years later there were hundreds of thousands of rows in the table variable and performance was terrible, so try and allow for some capacity planning when you make your decision!

    0 讨论(0)
  • 2020-11-22 05:47

    Consider also that you can often replace both with derived tables which may be faster as well. As with all performance tuning, though, only actual tests against your actual data can tell you the best approach for your particular query.

    0 讨论(0)
  • 2020-11-22 05:49

    It surprises me that no one mentioned the key difference between these two is that the temp table supports parallel insert while the table variable doesn't. You should be able to see the difference from the execution plan. And here is the video from SQL Workshops on Channel 9.

    This also explains why you should use a table variable for smaller tables, otherwise use a temp table, as SQLMenace answered before.

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