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

后端 未结 12 1352
抹茶落季
抹茶落季 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题