|
发表于 2020-3-19 23:45:01
|
显示全部楼层
参考:
--生成测试数据
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 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
--执行查询
select ID,isnull(dbo.f_getChild(ID),'') from BOM group by ID
go
--输出结果
/*
a bcdefg
b de
c fg
d
e
f
g
*/
--删除测试数据
drop function f_getChild
drop table BOM |
|