将5.3M记录插入临时表需要很长时间

时间:2018-10-12 12:58:50

标签: sql-server temp-tables

我正在将5308194个记录插入此#Temp表中,这大约需要8秒钟,并且认为它不需要那么多时间

是否有更好的方法来执行此操作,或者是否可以大容量插入,在插入之前创建临时表?

SELECT g.CustomerId, g.LogDate
INTO #Temp
FROM vwGuidelineLog g --nolock
WHERE g.LogDate >= '2017-10-01' 
  AND g.LogDate < DATEADD(DAY, 1, '2018-09-30')

DDL

CREATE VIEW [dbo].[vwGuidelineLog]
WITH SCHEMABINDING 
AS
    SELECT        
        GuidelineLogID, LogDate, FileName, CustomerID, GuidelineLinkId, CountryId
    FROM            
        dbo.GuidelineLog
    WHERE        
        (GuidelineLinkId IS NOT NULL)

聚集索引

CREATE UNIQUE CLUSTERED INDEX [IdX_vwGuidelineLog] 
ON [dbo].[vwGuidelineLog] ([GuidelineLogID] ASC)

LogDate的索引:

CREATE NONCLUSTERED INDEX [IDX_GuidelineLogDate] 
ON [dbo].[vwGuidelineLog] ([LogDate] ASC)

1 个答案:

答案 0 :(得分:1)

GuidelineLinkId上没有索引将无济于事,因为这意味着数据引擎需要扫描整个表。考虑到您有5,308,194行满足要求GuidelineLinkId不为空,并且logDate> ='2017-10-01'和LogDate

我个人将考虑在该列上添加索引(其他列上可能带有INCLUDE)。也许:

CREATE NONCLUSTERED INDEX IDX_GuidelineLinkId
    ON dbo.GuidelineLog (GuidelineLinkId ASC)
    INCLUDE (GuidelineLogID, LogDate,LogDate, FileName, CustomerID, CountryId);

Dan关于更改视图IDX_GuidelineLogDate的建议可能也是一个好主意:

ALTER INDEX [IDX_GuidelineLogDate]
    ON [dbo].[vwGuidelineLog] ([LogDate] ASC)
    INCLUDE (CustomerID);