--示例--示例数据
create table BomSub(parent_item varchar(10),sub_item varchar(10))
insert BomSub select 'A' ,'AA'
union  all    select 'A' ,'AB'
union  all    select 'AA','AAA'
union  all    select 'AA','AAB'
go--查询处理的存储过程
create proc p_qry
as
declare @t table(parent_item varchar(10),level int,path varchar(8000))
declare @l int
set @l=0
insert @t select distinct parent_item,@l,right(space(20)+parent_item,20)
from BomSub a
where not exists(
select * from BomSub where sub_item=a.parent_item)
while @@rowcount>0
begin
set @l=@l+1
insert @t select a.sub_item,@l,b.path+right(space(20)+a.sub_item,20)
from BomSub a,@t b
where a.parent_item=b.parent_item and b.level=@l-1
end
select parent_item=case level when 0 then '' else '|'+replicate('-',level) end+parent_item,level
from @t
order by path
go--调用
exec p_qry
go--删除测试
drop table BomSub
drop proc p_qry/*--结果parent_item               level  
------------------------- -------
A                         0
|-AA                      1
|--AAA                    2
|--AAB                    2
|-AB                      1(所影响的行数为 5 行)
--*/