有一个表:DepartTab,
有三个字段
DepartID DepartWBS DepartName
1 1 部门a
2 1.1 部门b
3 1.1.1 部门c
4 1.2 部门d
5 1.2.1 部门e
6 1.3 部门f
7 1.3.1 部门g
8 1.3.1.1 部门h
9 1.3.1.2 部门i要求查出DepartID>7的所有项,及它们所有父项的记录,比如说DepartID>7的记录为8和9,那么就要找出8和9及它们的父项(1.3.1.1、1.3.1.2、1.3.1、1.3、1)。
用sql来实现,有没有能实现的朋友。
有三个字段
DepartID DepartWBS DepartName
1 1 部门a
2 1.1 部门b
3 1.1.1 部门c
4 1.2 部门d
5 1.2.1 部门e
6 1.3 部门f
7 1.3.1 部门g
8 1.3.1.1 部门h
9 1.3.1.2 部门i要求查出DepartID>7的所有项,及它们所有父项的记录,比如说DepartID>7的记录为8和9,那么就要找出8和9及它们的父项(1.3.1.1、1.3.1.2、1.3.1、1.3、1)。
用sql来实现,有没有能实现的朋友。
@UpperIDs varchar(5000),
@ChildDept varchar(5000) output
ASDeclare @DeptID int, @Depts varchar(5000), @Rtn varchar(5000), @tmp varchar(5000)set @Depts = ','Declare cur_DeptID Cursor For
Select ID from Dept where @UpperIDs like '%,'+cast(upperid as varchar)+',%'Open cur_DeptID
Fetch Next From cur_DeptID into @DeptID
While @@Fetch_Status = 0
Begin
set @Depts = @Depts + cast(@DeptID as varchar) +','
Fetch Next From cur_DeptID into @DeptID
end
Close cur_DeptID
Deallocate cur_DeptIDif @Depts <> ','
begin
exec sp_GetDeptIDsFromUpperID @Depts,@Rtn output
if isnull(@Rtn,',') <> @Depts
set @Depts = isnull(@upperids,'')+ substring(isnull(@Rtn,','), 2, len(isnull(@Rtn,','))-1)
else
set @Depts = isnull(@upperids,'')+ substring(isnull(@Depts,','), 2, len(isnull(@Depts,','))-1)
end
else
set @Depts = @upperidsset @ChildDept = @Deptsreturn以前代码,仅供参考,这个代码是ID和UPID来实现的,只要改成你的模式就可以了