我创建了2个临时表,#Table1
是源,#Table2
是输出表。我必须遍历#Table1
上的每一行才能进行必要的计算,然后将每行插入#Table2
,因为计算还取决于#Table2
中的前一行。
我按照我想要的顺序拥有所有行,并使所有计算完美运行。唯一的问题是当我查看我的30,000行测试数据时,需要30多分钟。这意味着当我将查询扩展到超过2,000,000行的全部范围时,这将花费太长时间。
示例表:
我在下面提供了遍历#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
如何根据此示例加快插入语句的速度?
答案 0 :(得分:0)
性能不在“插入”本身。它位于用于创建数据的查询中(select
的{{1}}部分)。要解决此问题,请考虑以下事项。
确保insert
中的id
列包含索引:
#table1
并确保create index on #table1(id);
有一个索引:
#table2(shipment)