Поскольку элемент здесь не имеет смысла, я удалил его из sql.
declare @t table(order1 varchar(5), product varchar(6), seqcheck int)
insert @t values('OR-01','PRD-01',70)
insert @t values('OR-01','PRD-02',15)
insert @t values('OR-01','PRD-03',55)
;with
b as
(
select order1, product, seqcheck - 30 seqcheck, case when seqcheck > 30 then 30 else seqcheck end quantity, 1 seq, 1 workorder
from @t
where product = 'PRD-01'
union all
select order1, product, seqcheck - 30, case when seqcheck > 30 then 30 else seqcheck end quantity, 1 seq, workorder + 1
from b
where seqcheck > 0
union all
select t.order1, t.product, t.seqcheck + b.seqcheck, case when t.seqcheck + b.seqcheck >= 0 then -b.seqcheck else t.seqcheck end quantity, seq + 1, workorder
from b join @t t on
cast(stuff(b.product, 1,4, '') as int) = cast(stuff(t.product, 1,4, '') as int) - 1
where b.seqcheck <= 0
)
select order1 [order], 'WO-' + left('000'+ cast(workorder as varchar(4)), 4) workord, right('000'+ cast(seq as varchar(3)), 3) seq, product, quantity from b
option(MAXRECURSION 0)
Результат:
order workord seq product quantity
----- ------- ---- ------- -----------
OR-01 WO-0001 001 PRD-01 30
OR-01 WO-0002 001 PRD-01 30
OR-01 WO-0003 001 PRD-01 10
OR-01 WO-0003 002 PRD-02 15
OR-01 WO-0003 003 PRD-03 5
OR-01 WO-0004 001 PRD-03 30
OR-01 WO-0005 001 PRD-03 20