--建立測試環境
Create Table strucinfo
(strucode Int,
locname Varchar(10),
fatherid Int,
slevels Int
)
Insert strucinfo Select 1, 'A', 0 , 1
Union All Select 2, 'A1', 1 , 2
Union All Select 3, 'A11', 2 , 3
Union All Select 4, 'A12', 2 , 3
Union All Select 5, 'A121', 4 , 4
Union All Select 6, 'A3', 1 , 2
Union All Select 7, 'A31', 6 , 3
GO
--建立函數
Create Function GetChildren(@strucode Int)
Returns @Tree Table (strucode Int, locname Varchar(10), fatherid Int)
As
Begin
Insert @Tree Select strucode, locname, fatherid From strucinfo Where strucode = @strucode
While @@Rowcount > 0
Insert @Tree Select A.strucode, A.locname, A.fatherid From strucinfo A Inner Join @Tree B On A.fatherid = B.strucode And A.strucode Not In (Select strucode From @Tree)
Return
End
GO
--測試
Select locname From dbo.GetChildren(2)
Select locname From dbo.GetChildren(6)
GO
--刪除測試環境
Drop Table strucinfo
Drop Function GetChildren
--結果
/*
locname
A1
A11
A12
A121