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

后端 未结 12 1128
抹茶落季
抹茶落季 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:35

    Differences between Temporary Tables (##temp/#temp) and Table Variables (@table) are as:

    1. Table variable (@table) is created in the memory. Whereas, a Temporary table (##temp/#temp) is created in the tempdb database. However, if there is a memory pressure the pages belonging to a table variable may be pushed to tempdb.

    2. Table variables cannot be involved in transactions, logging or locking. This makes @table faster then #temp. So table variable is faster then temporary table.

    3. Temporary table allows Schema modifications unlike Table variables.

    4. Temporary tables are visible in the created routine and also in the child routines. Whereas, Table variables are only visible in the created routine.

    5. Temporary tables are allowed CREATE INDEXes whereas, Table variables aren’t allowed CREATE INDEX instead they can have index by using Primary Key or Unique Constraint.

提交回复
热议问题