BOM 创建用户定义函数,每个子节点de父节点的信息
--生成测试数据
createtable BOM(ID int,parentID int,sClassName varchar(10))
insertinto BOM values(1,0,'1111' )
insertinto BOM values(2,1,'1111_1' )
insertinto BOM values(3,2,'1111-1-1' )
insertinto BOM values(4,3,'1111-1-1-1')
insertinto BOM values(5,1,'1111-2' )
go
--创建用户定义函数,每个子节点de父节点的信息
createfunction f_getParent(@IDint)
returnsvarchar(40)
as
begin
declare@retvarchar(40)
whileexists(select1from BOM where ID=@IDand parentID<>0)
begin
select@ID=b.ID,@ret=','+rtrim(b.ID)+isnull(@ret,'')
from
BOM a,BOM b
where
a.ID=@IDand b.ID=a.parentID
end
set@ret=stuff(@ret,1,1,'')
return@ret
end
go
--执行查询
select ID,isnull(dbo.f_getParent(ID),'') as parentID from BOM
go
--输出结果
/*
ID parentID
----------- ----------------------------------------
1
2 1
3 1,2
4 1,2,3
5 1
*/
--删除测试数据
dropfunction f_getParent
droptable BOM
go