|
reference:
-Generate test data
create table BOM (ID VARCHAR (10), PID VARCHAR (10))
insert into BOM select 'a', NULL
insert into BOM select 'b', 'a'
insert into BOM select 'c', 'a'
insert into BOM select 'd', 'b'
insert into BOM select 'e', 'b'
insert into BOM select 'f', 'c'
insert into BOM select 'g', 'c'
go
--Create user-defined functions
create function f_getChild (@ID VARCHAR (10))
returns varchar (8000)
as
begin
declare @i int, @ ret varchar (8000)
declare @t table (ID VARCHAR (10), PID VARCHAR (10), Level INT)
set @i = 1
insert into @t select ID, PID, @ i from BOM where PID = @ID
while @@ rowcount <> 0
begin
set @i = @i + 1
insert into @t
select
a.ID, a.PID, @ i
from
BOM a, @ t b
where
a.PID = b.ID and b.Level = @ i-1
end
select @ret = isnull (@ret, '') + ID from @t
return @ret
end
go
--Execute query
select ID, isnull (dbo.f_getChild (ID), '') from BOM group by ID
go
-Output results
/ *
a bcdefg
b de
c fg
d
e
f
g
* /
--Delete test data
drop function f_getChild
drop table BOM |
|