如何加快反复重复插入事务的速度

时间:2014-02-14 16:33:23

标签: sql insert

我创建了2个临时表,#Table1是源,#Table2是输出表。我必须遍历#Table1上的每一行才能进行必要的计算,然后将每行插入#Table2,因为计算还取决于#Table2中的前一行。

我按照我想要的顺序拥有所有行,并使所有计算完美运行。唯一的问题是当我查看我的30,000行测试数据时,需要30多分钟。这意味着当我将查询扩展到超过2,000,000行的全部范围时,这将花费太长时间。

示例表:

Example Tables

我在下面提供了遍历#Table1中每条记录以提出#Table2的解决方案。

exec [database_name].dbo.drop_if_exists '#Table2'
create table #Table2 (ID int, Shipment varchar(8), Delivery int, Arrival datetime, ETA datetime, ETA_TimeStamp datetime, Compliant int)

declare @z int
declare @currentShipment varchar(8)
declare @currentStop int
declare @previousID int
declare @previousETA datetime

set @z = 1
while @z <= (Select max(ID) from #Table1)
Begin
Set @currentShipment = (Select Shipment from #Table1 where ID = @z)
Set @currentStop  = (Select Delivery from #Table1 where ID = @z)
Set @previousID = (Select max(ID) from #Table2 where Shipment = @currentShipment AND Delivery = @currentStop AND ID < @Z AND Compliant = 1)
Set @previousETA = (Select ETA from #Table2 where ID = @previousID)

 if (Select count(Shipment) from #Table2 where Shipment = @currentShipment AND Delivery = @currentStop AND ID < @Z AND Compliant = 1) = 0
    BEGIN
    insert into #Table2 Select ID
    , Shipment
    , Delivery
    , Arrival
    , ETA
    , ETA_Timestamp
    , Compliant_Prelim as [Compliant]
    from #Table1
    where ID = @Z
    END

 if (Select count(Shipment) from #Table2 where Shipment = @currentShipment AND Delivery = @currentStop AND ID < @Z AND Compliant = 1) > 0
    BEGIN
    insert into #Table2 Select ID
    , Shipment
    , Delivery
    , Arrival
    , ETA
    , ETA_Timestamp
    , case when (Select Compliant_Prelim from #Table1 where ID = @z) = 1
        AND ETA_TimeStamp <= dateadd(hh, -1, @previousETA)
        then 1
        else 0 end as [Compliant]
    from #Table1
    where ID = @Z
    END
Set @z = @z + 1
End

Select * from #Table2

如何根据此示例加快插入语句的速度?

1 个答案:

答案 0 :(得分:0)

性能不在“插入”本身。它位于用于创建数据的查询中(select的{​​{1}}部分)。要解决此问题,请考虑以下事项。

确保insert中的id列包含索引:

#table1

并确保create index on #table1(id); 有一个索引:

#table2(shipment)