所以我有这个查询,它通过 id 搜索 id 并相应地计算成本。但是速度很慢,我想了解如何将其转换为基于集合的操作。
因此,根据我们的情况,我们以不同的方式计算我们的模型成本。
当用户更新驱动程序时,我们可以根据更改的位置在整个驱动程序列上运行更新。
但是在计算建模成本时。我们逐行进行,因为固定成本不同,然后除以月。我已经粘贴了下面的代码。通过基于集合的操作还有办法做到这一点吗?
首先,我们根据使用更新更改的值更新同一表中的驱动程序,然后逐行更新建模成本(这真的很慢)
代码 :
SELECT @rowCounter = 1, @totalrows = @@ROWCOUNT
WHILE @rowCounter <= @totalrows
BEGIN
SELECT @currentId = tempId
FROM @temp
WHERE row = @rowCounter
SELECT
@newModeledCost =
case when not exists (select 1 from dbo.DIMSTD_SCENARIO where SCENARIO0_Name = SCENARIO and SCENARIO2_Name = 'Model') then
ISNULL(DriverValue1,0)*ISNULL(DriverValue2,0)*ISNULL(UnitA,0)*ISNULL(UnitB,0)+ISNULL(FixedCost,0)
-- normal allocation for all scenarios
else
(ISNULL(unita,0) * (ISNULL(DriverValue1,0)/ISNULL(NULLIF(DriverValue2,0),1))* ISNULL(UnitB,0))+ISNULL(FixedCost,0)
--(ISNULL(unita,0) * (ISNULL(DriverValue1,0)/ISNULL(DriverValue2,0))*ISNULL(UnitB,0))+ISNULL(FixedCost,0)
-- allocation for model scenarios
end
,
@oldModeledCost = ISNULL(ModeledCost,0),
@newOct = (ISNULL(@newModeledCost,0) * (ISNULL(Oct, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newNov = (ISNULL(@newModeledCost,0) * (ISNULL(Nov, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newDec = (ISNULL(@newModeledCost,0) * (ISNULL(Dec, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newJan = (ISNULL(@newModeledCost,0) * (ISNULL(Jan, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newFeb = (ISNULL(@newModeledCost,0) * (ISNULL(Feb, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newMar = (ISNULL(@newModeledCost,0) * (ISNULL(Mar, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newApr = (ISNULL(@newModeledCost,0) * (ISNULL(Apr, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newMay = (ISNULL(@newModeledCost,0) * (ISNULL(May, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newJun = (ISNULL(@newModeledCost,0) * (ISNULL(Jun, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newJul = (ISNULL(@newModeledCost,0) * (ISNULL(Jul, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newAug = (ISNULL(@newModeledCost,0) * (ISNULL(Aug, 0) /ISNULL(NULLIF(@oldModeledCost,0),1))),
@newSep = (ISNULL(@newModeledCost,0) * (ISNULL(Sep, 0) /ISNULL(NULLIF(@oldModeledCost,0),1)))
FROM dbo.TBF_BUDGETExpenses
WHERE BudgetId = @currentId
--and not exists (select 1 from dbo.DIMSTD_SCENARIO where SCENARIO0_Name = SCENARIO and SCENARIO2_Name = 'Model')
UPDATE dbo.TBF_BUDGETExpenses
SET ModeledCost = @newModeledCost,
Oct = @newOct,
Nov = @newNov,
Dec = @newDec,
Jan = @newJan,
Feb = @newFeb,
Mar = @newMar,
Apr = @newApr,
May = @newMay,
Jun = @newJun,
Jul = @newJul,
Aug = @newAug,
Sep = @newSep,
Username = 'Cascade',
lastmodified = getdate()
WHERE BudgetId = @currentId
AND @oldModeledCost <> 0
Print 'Record Update ' + CAST(@currentId AS VARCHAR(15))
SET @rowCounter = @rowCounter + 1
END