22,209
社区成员
发帖
与我相关
我的任务
分享
create table #EnterPrise
(
Department nvarchar(50),--部门名称
ParentDept nvarchar(50),--上级部门
DepartManage nvarchar(30)--部门经理
)
insert into #EnterPrise select '技术部','总经办','Tom'
insert into #EnterPrise select '商务部','总经办','Jeffry'
insert into #EnterPrise select '商务一部','商务部','ViVi'
insert into #EnterPrise select '商务二部','商务部','Peter'
insert into #EnterPrise select '程序组','技术部','GiGi'
insert into #EnterPrise select '设计组','技术部','yoyo'
insert into #EnterPrise select '专项组','程序组','Yue'
insert into #EnterPrise select '总经办','','Boss'
--查询部门经理是Tom的下面的部门名称
;with hgo as
(
select *,0 as rank from #EnterPrise where DepartManage='Tom'
union all
select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.ParentDept=h1.Department
)
select * from hgo
/*
Department ParentDept DepartManage rank
--------------- -------------------- ----------------------- -----------
技术部 总经办 Tom 0
程序组 技术部 GiGi 1
设计组 技术部 yoyo 1
专项组 程序组 Yue 2
*/
--查询部门经理是GiGi的上级部门名称
;with hgo as
(
select *,0 as rank from #EnterPrise where DepartManage='GiGi'
union all
select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.Department=h1.ParentDept
)
select * from hgo
/*
Department ParentDept DepartManage rank
-------------------- ---------------------- ----------- -----------
程序组 技术部 GiGi 0
技术部 总经办 Tom 1
总经办 Boss 2
*/
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ws_hgo/archive/2010/01/31/5274571.aspx
create table BOM(ID INT,PID INT)
insert into BOM select 1,0
insert into BOM select 2,1
insert into BOM select 3,1
insert into BOM select 4,2
insert into BOM select 5,0
insert into BOM select 6,3
insert into BOM select 7,6
go
create proc Proc_kq_GetSubDptId
@sDeptID VARCHAR(100),
@sAllSubDeptID varchar(1000) output
as
declare @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT)
declare @i int
set @i=1
insert into @t select ID,PID,@i from BOM where id=@sDeptID
while @@rowcount<>0
begin
set @i=@i+1
insert into @t select a.ID,a.PID,@i from BOM a,@t b where a.PID=b.ID and b.Level=@i-1
end
select @sAllSubDeptID=isnull(@sAllSubDeptID+',','')+ltrim(id) from @t order by level
go
--调用
declare @childids varchar(1000)
exec Proc_kq_GetSubDptId 1,@childids output
select @childids as '自身加子节点'
--结果:
自身加子节点
------------
1,2,3,4,6,7