34,590
社区成员
发帖
与我相关
我的任务
分享
DECLARE @depno int;
SET @depno=3;
with cte(部门编号,部门名称,上级部门编号,lvl)
AS
(
SELECT 部门编号,部门名称,上级部门编号,0 FROM # WHERE 部门编号=@depno
UNION ALL
SELECT tb.部门编号,tb.部门名称,tb.上级部门编号,lvl+1 FROM # tb JOIN cte ON tb.上级部门编号=cte.部门编号
)
select 部门编号,部门名称,上级部门编号,lvl '部门阶层' from cte
with cte as
(
select * from tab where 上级部门编号 = 0
union all
select tab.* from tab join cte on tab.上级部门编号= cte.部门编号
)
select * from cte
create table #t(部门编号 int,部门名称 varchar(10), 上级部门编号 int)
insert into #t
select 1,'tes1',0 union all
select 2,'tes2',0 union all
select 3,'tes3',2 union all
select 4,'tes4',1union all
select 5,'tes5',3union all
select 6,'tes6',3union all
select 7,'tes7', 4
with c (部门编号,部门名称,上级部门编号) as
(
select 部门编号,部门名称,上级部门编号 from #t where 部门编号=2
union all
select a.部门编号,a.部门名称,a.上级部门编号 from #t a join c on a.上级部门编号=c.部门编号
)
select *from c
2 tes2 0
3 tes3 2
5 tes5 3
6 tes6 3
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(部门编号 int, 部门名称 varchar(8), 上级部门编号 int)
insert into #
select 1, 'tes1', 0 union all
select 2, 'tes2', 0 union all
select 3, 'tes3', 2 union all
select 4, 'tes4', 1 union all
select 5, 'tes5', 3 union all
select 6, 'tes6', 3 union all
select 7, 'tes7', 4
declare @dept int
set @dept = 2;
with t as
(
select * from # where 部门编号 = @dept
union all
select #.* from # join t on #.上级部门编号 = t.部门编号
)
select * from t
/*
部门编号 部门名称 上级部门编号
----------- -------- -----------
2 tes2 0
3 tes3 2
5 tes5 3
6 tes6 3
*/
with cte as
(
select * from tab where 上级部门编号 = 0
union all
select * from tab join cte on tab.上级部门编号= cte.部门编号
)
select * from cte