62,074
社区成员
发帖
与我相关
我的任务
分享
CREATE Function GetChildbase(@UnitId bigint, @Level int)
Returns @Child Table([UnitId] int ,[username] varchar(64),[ParentUnitId] int)
As
Begin
If @Level < 1 --如果参数@Level小于“1”,则得到所有子单位
Begin
Insert @Child
Select ID,UserName,Pid
From [Login] Where inure=1 and [Pid] = @UnitId
While @@ROWCOUNT > 0
Begin
Insert @Child
Select B.ID,B.UserName,B.Pid
From @Child A Inner Join [Login] B
On b.inure=1 and A.[UnitId]=B.[Pid]
Where B.[Pid] Not In
(Select Distinct [ParentUnitId] From @Child)
End
Insert @Child
Select ID,UserName,Pid
From [Login] Where inure=1 and [id] = @UnitId
End
Else
Begin
Set @level = @Level -1
Insert @Child
Select id,username,Pid
From [Login] Where inure=1 and [Pid]=@UnitId
While @@ROWCOUNT > 0 And @level > 0
Begin
Set @level = @Level -1
Insert @Child
Select B.id,B.Username,B.Pid
From @Child A Inner Join [Login] B
On b.inure=1 and A.[UnitId]=B.[Pid]
Where B.[Pid] Not In
(Select Distinct [ParentUnitId] From @Child)
End
Insert @Child
Select ID,UserName,Pid
From [Login] Where inure=1 and [id] = @UnitId
End
Return
End