我想出了這個感謝來自其他來源的提示。 running-totals nested-cursors-w-errors 與2012年或以後的over(order by)選項相比,它非常慢。
DECLARE @FiFo TABLE
(
RctNumb | Item | QTYRct | RctCostPerItem | DATERECD
OHBFIFOCOST decimal(19,5),
OHB decimal(19,5),
SumRctInvcd decimal(19,5),
QtyToCost decimal(19,5),
ITEM nvarchar(65) PRIMARY KEY,
ReportDate [datetime2](0)
);
declare @ITEM as char(31)
declare @OHB as decimal(19,5)
declare @outer_cursor cursor
declare @inner_cursor cursor
declare @RctNumb nvarchar(32)
declare @RCTITEM as nvarchar(65)
declare @QTYRct decimal(19,5)
declare @SumRctInvcd decimal(19,5)
declare @QtyToCost decimal(19,5)
declare @RctCostPerItem decimal(19,5)
declare @OHBCOST decimal(19,5)
declare @OHBrem decimal(19,5)
declare @rowIndex int
declare @DATERECD datetime
declare @fetch_outer_cursor int
declare @fetch_inner_cursor int
set @outer_cursor = cursor static local for
Select
ITEM
,OHB
from ItemMaster
where OHB > 0
/*loop through top level cursor*/
open @outer_cursor
fetch next from @outer_cursor into @ITEM, @OHB
select @fetch_outer_cursor = @@FETCH_STATUS
while @fetch_outer_cursor = 0
begin
/*loop through second level cursor*/
set @inner_cursor = cursor static local for
select
RctNumb
,QTYRct
,RctCostPerItem
,ITEM
,DATERECD
,rowIndex
from RctTbl
Where ITEM = @ITEM
Order By rowIndex desc
open @inner_cursor
fetch next from @inner_cursor into @RctNumb, @QTYRct, @RctCostPerItem, @RCTITEM, @DATERECD, @rowIndex
set @fetch_inner_cursor = @@FETCH_STATUS
while @OHBrem >0 and @fetch_inner_cursor = 0
begin
set @OHBrem = @OHBrem - @QTYRct
set @QtyToCost = case
When @SumRctInvcd + @QTYRct <= @OHB Then @QTYRct
else @OHB - @SumRctInvcd
end
set @OHBCOST = case
When @SumRctInvcd + @QTYRct <= @OHB Then @OHBCOST + (@QtyToCost * @RctCostPerItem)
else @OHBCOST + (@QtyToCost * @RctCostPerItem)
end
set @SumRctInvcd = @SumRctInvcd + @QtyToCost
fetch next from @inner_cursor into @RctNumb, @QTYRct, @RctCostPerItem, @RCTITEM, @DATERECD, @rowIndex
set @fetch_inner_cursor = @@FETCH_STATUS
end
close @inner_cursor
deallocate @inner_cursor
INSERT @FiFo(OHBFIFOCOST, OHB, ITEM, ReportDate, QtyToCost, SumRctInvcd)
SELECT @OHBCOST, @OHB, @ITEM, GETDATE(), @QtyToCost, @SumRctInvcd;
fetch next from @outer_cursor into @ITEM, @OHB
set @fetch_outer_cursor = @@FETCH_STATUS
end
close @outer_cursor
deallocate @outer_cursor
select * from @FiFo
爲什麼四個空間前綴不能保留我的空白? – stinkyjak
因爲在標題和下一段落之間需要**空行**來獲得該效果 –
您需要的是一個正在運行的總數。 2012年,它非常簡單和高效。在2008R2中,您需要執行更復雜的SQL,其自身的非等值連接速度要慢得多。 –