declare cFoldersOnly Cursor local forward_only static read_only for select tocid, parentid, name from toc where etype = 0 and parentid <> 2; declare @ctocid integer; declare @cparentid integer; declare @cname varchar(255); declare cImageSize cursor local forward_only static read_only for select t.parentid as folderid, sum(convert(bigint, d.img_size)) as docsize from doc as d join toc as t on d.tocid = t.tocid where t.parentid <> 2 group by t.parentid; declare cEdocSize cursor local forward_only static read_only for select d.parentid as folderid, sum(convert(bigint, d.edoc_size)) as docsize from toc as d where d.parentid <> 2 and d.edoc_storeid is not null group by d.parentid; declare @cfolderid integer; declare @cdocsize bigint; declare @lFolderTable table( tocid integer unique, path varchar(255), edoc_size bigint, img_size bigint); declare @lpath varchar(255); declare @lparentid integer; open cFoldersOnly; fetch next from cFoldersOnly into @ctocid, @cparentid, @cname; while @@fetch_status = 0 begin select @lpath = @cname, @lparentid = @cparentid; while @lparentid > 5 begin select @lpath = (name + '\' + @lpath), @lparentid = parentid from toc where tocid = @lparentid; end; insert into @lFolderTable values (@ctocid, @lpath, 0, 0); fetch next from cFoldersOnly into @ctocid, @cparentid, @cname; end; close cFoldersOnly; deallocate cFoldersOnly; open cImageSize; fetch next from cImageSize into @cfolderid, @cdocsize; while @@fetch_status = 0 begin update @lFolderTable set img_size = @cdocsize where tocid = @cfolderid; fetch next from cImageSize into @cfolderid, @cdocsize; end; close cImageSize; deallocate cImageSize; open cEdocSize; fetch next from cEdocSize into @cfolderid, @cdocsize; while @@fetch_status = 0 begin update @lFolderTable set edoc_size = @cdocsize where tocid = @cfolderid; fetch next from cEdocSize into @cfolderid, @cdocsize; end; close cEdocSize; deallocate cEdocSize; select path, (edoc_size + img_size) as size from @lFolderTable order by path;