插入#table要比插入@table快得多。为什么呢?

时间:2017-10-10 13:32:44

标签: sql-server tsql

这是我的查询的基本结构。如果我插入#temp table,那么查询将在大约两秒钟内运行:

IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp

declare @table table              
(
    locationKey int,
    DateKey date,         
    totalcount bigint,
    locationCount int,
    LastDateOnAir date,
    Aging int
)       

;with cteSum as 
(
    select 
    fact.locationid as 'locationKey'
    ,cast([datetime] as date) as 'datekey'
    ,sum(totalcount) as 'totalcount'
    ,count(fact.locationCell) as 'locationCount'
    ,sum(period) as 'period'
    FROM [dbo].[MasterTable] fact inner join Dim dim on
    fact.locationid = dim.location
    WHERE cast([datetime] as date) >= '2017-09-21'
    group by
    fact.locationid, cast([datetime] as date)
) 
select         
locationKey, datekey, totalcount, locationCount into #temp
FROM cteSum
--insert into @table
--(locationKey, datekey, totalcount, locationCount)
--select         
--locationKey, datekey, totalcount, locationCount
--FROM cteSum

如果我插入@table变量,整个查询将在大约8秒内运行。 insert到表变量会为执行添加六秒钟。

表变量是否比临时表慢得多?我们正在谈论插入的2,000行。

感谢。

1 个答案:

答案 0 :(得分:1)

测试性能:

  1. OPTION(RECOMPILE)
  2. 选项(MAXDOP 1)
  3. SET STATISTICS TIME ON
  4. 临时表&变量表对象几乎相同......