2

我希望你们能帮助我。我有以下 SQL 查询,我认为它不是很繁重但大约需要 5 分钟才能完成。如果您有其他方法可以完成此操作,请告诉我:

update rep
set rep.StatusID= 2,
rep.Available= 1,
rep.User= @user
from dbo.MCP_Rep_Compensation_Plan rep
left join dbo.MCP_Compensation_Plan compensationplan on compensationplan.Compensation_Plan_ID = @compplan_id and compensationplan.Active = 1
left join dbo.MRRS_Cycle actualcycle on actualcycle.CycleID = compensationplan.CycleID and actualcycle.Active = 1
left join dbo.MRRS_Cycle lastcycle on lastcycle.Consecutive = actualcycle.Consecutive -1 and lastcycle.Active = 1
where rep.Active = 1 and rep.ID_Compensation_Plan = @compplan_id and exists(
select OrderID
from dbo.MCP_Orders
where Active = 1 and Order_cycle = lastcycle.CycleID and OrderRepID = rep.RepID
and Order_Status in(28,30))
4

1 回答 1

2

我确实看到您的查询可以在某些地方重写,但如果不查看您的执行计划并确保您有适当的索引,我不确定它会有多大帮助。

例如,确保在第一次连接到补偿计划表时包含实际连接条件。通过加入compensationplan.Compensation_Plan_ID和来做到这一点rep.ID_Compensation_Plan

另外,我认为不需要,OUTER JOINs因为您在相关存在子查询中使用了其中一些表。

这是更新的查询:

update rep
    set rep.StatusID= 2,
    rep.Available= 1,
    rep.User= @user
from dbo.MCP_Rep_Compensation_Plan rep
    join dbo.MCP_Compensation_Plan compensationplan on 
         compensationplan.Compensation_Plan_ID = rep.ID_Compensation_Plan and compensationplan.Active = 1
    join dbo.MRRS_Cycle actualcycle on 
          actualcycle.CycleID = compensationplan.CycleID and actualcycle.Active = 1
    join dbo.MRRS_Cycle lastcycle on 
          lastcycle.Consecutive = actualcycle.Consecutive -1 and lastcycle.Active = 1
where rep.Active = 1 
    and rep.ID_Compensation_Plan = @compplan_id 
    and exists(
        select OrderID
        from dbo.MCP_Orders
        where Active = 1 
            and Order_cycle = lastcycle.CycleID 
            and OrderRepID = rep.RepID
            and Order_Status in(28,30)
    )
于 2013-07-13T16:49:13.233 回答