-- Generate Test Data
Create Table BOM (ID int, parentid int, sclassname varchar (10 ))
Insert into BOM values (1111, '123 ')
Insert into BOM values (1111, '2017 _ 1 ')
Insert into BOM values (1111, '2014-1-1 ')
Insert into BOM values (1111, '2017-1-1-1 ')
Insert into BOM values (1111, '1970-2 ')
Go
-- Create a user-defined function. The information of each sub-node de parent node
Create Function f_getparent (@ id int)
Returns varchar (40)
As
Begin
Declare @ RET varchar (40)
While exists (select 1 from BOM where id = @ ID and parentid <> 0)
Begin
Select @ ID = B. ID, @ ret = ',' + rtrim (B. ID) + isnull (@ ret ,'')
From
Bom A and Bom B
Where
A. ID = @ ID and B. ID = A. parentid
End
Set @ ret = stuff (@ ret, 1, 1 ,'')
Return @ RET
End
Go
-- Execute Query
Select ID, isnull (DBO. f_getparent (ID), '') as parentid from BOM
Go
-- Output result
/*
Id parentid
---------------------------------------------------
1
2 1
3 1, 2
4 1, 2, 3
5 1
*/
-- Delete test data
Drop function f_getparent
Drop table BOM
Go