--建立环境
create Table #BOM(ParentItem varchar(10),         ChildItem  varchar(10))
insert #bom values('A','B')
insert #bom values('A','C')
insert #bom values('A','D')
insert #bom values('A','E')
insert #bom values('B','F')
insert #bom values('B','G')
insert #bom values('D','H')
insert #bom values('D','I')
insert #bom values('F','J')
insert #bom values('F','K')--临时表
select * into #xxx from #bom--深度
declare @tmp1 table (a varchar(10),b varchar(10),c int,d int) --存树放顺序,及子树号
declare @tmp2 table (a varchar(10),b varchar(10),c int) --存放层次declare @i int,@j varchar(100)
set @j=1while exists (select 1 from #xxx)
begin
  set @i=1
  insert @tmp1 select top 1 *,@i,@j from #xxx
  while exists(select 1 from #xxx a,@tmp1 b where a.parentitem=b.b and a.childitem not in (select b from @tmp1))
  begin
    insert @tmp1 select top 1 a.*,@i+1,@j from  #xxx a,@tmp1 b where a.parentitem=b.b and a.childitem not in (select b from @tmp1) order by a.parentitem desc
    set @i=@i+1
  end
  delete #xxx where ChildItem in (select b from @tmp1)
  set @j=@j+1
endset @i=1
insert @tmp2 select *,1 from #bom where parentitem=(select top 1 parentitem from #bom)while exists(select 1 from #bom a,@tmp2 b where a.parentitem=b.b and a.childitem not in (select b from @tmp2))
begin
  insert @tmp2 select a.*,@i+1 from  #bom a,@tmp2 b where a.parentitem=b.b and a.childitem not in (select b from @tmp2)
  set @i=@i+1
endselect replicate('.',b.c-1)+rtrim(b.c) 层次,a.b from @tmp1 a,@tmp2 b where a.b=b.b order by a.d,a.c
go
drop table #bom,#xxx                                                       --MVP