SQL 服务器温度 Table 具有高排序

SQL Server Temp Table with a High Sort

我不明白为什么我会在包含非集群的 temp table 上得到 Sort Cost

Do I need to build the Statistics after the creating the index?

CREATE TABLE #TempGuidelineLog
(
[ID] int identity(1,1) NOT NULL,
[CustomerId] int,[LogDate] DateTime,
CONSTRAINT [PK_#TempTable'] PRIMARY KEY CLUSTERED 
    ([ID] ASC) WITH (PAD_INDEX = OFF
     ,STATISTICS_NORECOMPUTE = OFF
     ,IGNORE_DUP_KEY = OFF
     ,ALLOW_ROW_LOCKS = ON
     ,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

INSERT #TempGuidelineLog ([CustomerId], [LogDate]) 
SELECT g.CustomerId, g.LogDate FROM vwGuidelineLog  g
where g.LogDate >= '2017-10-01' and g.LogDate < dateadd(day, 1, '2018-09-30')

CREATE NONCLUSTERED INDEX ix_temp1Customer ON #TempGuidelineLog (CustomerId)
INCLUDE ([LogDate])

    select
    g.*,
    a.StateId, 
    a.CountryId
    into #TempCustomerAddress
    from #TempGuidelineLog g
    JOIN [vwCustomerAddress] a ON a.CustomerId = g.CustomerId

改进的机会

  • 首先创建临时 table
  • 在其上放置聚集索引而不是与堆共舞
  • 如果 customerid 是唯一的,则使该索引 PK
  • 尝试分批处理这些数据,而不是一次全部处理

代码:

CREATE TABLE #TempGuidelineLog
(
  [CustomerId] int NOT NULL,
  [LogDate] DateTime NOT NULL
)
CREATE CLUSTERED INDEX ix_temp1Customer ON #TempGuidelineLog (CustomerId)

INSERT #TempGuidelineLog ([CustomerId], [LogDate]) 
SELECT g.CustomerId, g.LogDate FROM vwGuidelineLog  g
where g.LogDate >= '2017-10-01' and g.LogDate < dateadd(day, 1, '2018-09-30')

如果需要,则无法避免排序。寻找未排序的日期会导致...隐式排序或循环+扫描。并且排序 5M+ 行不可能有零成本。

请注意,您粘贴的最后一个计划包含额外插入的相同数据。我认为这是一个错字,所以删除它可以避免不必要的工作量。