BOM資料排序及分級顯示

2021-04-01 01:42:41 字數 1291 閱讀 2041

bom資料排序及分級顯示

--示例資料:

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問題描述:

parent_item是父項,sub_item是子項,根據根據父子關係排序,並生成每個專案的層次。對於示例資料,要求結果如下:

parent_item  level

----------- -------

a           0

|-aa        1

|--aaa      2

|--aab      2

|-ab        1

(所影響的行數為 5 行)

--查詢處理的儲存過程

create proc p_qry

asdeclare @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

endselect parent_item=case level when 0 then '' else '|'+replicate('-',level) end+parent_item,

level

from @t

order by path

go--呼叫

exec p_qry

原帖位址

BOM資料排序及分級顯示

bom資料排序及分級顯示 示例資料 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 a...

BOM資料排序及分級顯示

bom資料排序及分級顯示 示例資料 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 a...

BOM資料排序及分級顯示

bom資料排序及分級顯示 示例資料 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 a...