средствами sql было не быстрее, только лишь запутаннее.
строим дерево справочника товаров:
create table #Tree
(
id char(9) not null,
parentid char(9) null,
descr varchar(100) null,
isfolder numeric(1, 0) not null,
lvl int not null,
sort varbinary(200) null,
ident int identity
)
declare @lvl int,
@void char(9)
set @void = ' 0 '
set @lvl = 1
-- создать корень
insert into #Tree (id, parentid, descr, isfolder, lvl, sort)
select @void, @void, NULL, 0 , 0, NULL
-- заполнить элементами первого уровня
insert into #Tree (id, parentid, descr, isfolder, lvl, sort)
select id, parentid, descr, isfolder, @lvl, cast(0 as binary(4))
from sc62 (nolock)
where (parentid = @void)
order by isfolder, cast(descr as varbinary(100))
while (@@rowcount > 0) begin
set @lvl = @lvl + 1
insert into #Tree (id, parentid, descr, isfolder, lvl, sort)
select t.id, t.parentid, t.descr, t.isfolder, @lvl, tt.sort + cast(tt.ident as binary(4))
from sc62 t (nolock)
join #Tree tt
on (tt.id = t.parentid) and (tt.lvl = @lvl - 1)
order by t.isfolder, cast(t.descr as varbinary(100))
end
update #Tree set sort = sort + cast(ident as binary(4))
связываем его с таблицей остатков
select
t.id id, o.qty as qty,
t.isfolder, t.lvl, t.parentid, t.sort
into #Main
from #Tree t
left join #Remains o
on (o.id = t.id)
считаем итоги
declare @maxlevel int
select @maxlevel = max(lvl) from #Main
while (@maxlevel >= 0) begin
set @maxlevel = @maxlevel - 1
update #Main
set
qty = (
select isnull(sum(mm.qty),0)
from #Main mm
where (mm.parentid = #Main.id)
)
where (#Main.lvl = @maxlevel) and (#Main.isfolder < 2)
end
добавить детализацию по складу сюда - уже кучу кода лопатить.