有一张部门表:
部门编号 部门名称 上级部门编号
1 tes1 0
2 tes2 0
3 tes3 2
4 tes4 1
5 tes5 3
6 tes6 3
7 tes7 4现在要通过一条sql语句列出所有该部门及子部门,子部门层级不限。 如部门编是2 要怎么写得到下面的内容,2 tes2 0
3 tes3 2
5 tes5 3
6 tes6 3
部门编号 部门名称 上级部门编号
1 tes1 0
2 tes2 0
3 tes3 2
4 tes4 1
5 tes5 3
6 tes6 3
7 tes7 4现在要通过一条sql语句列出所有该部门及子部门,子部门层级不限。 如部门编是2 要怎么写得到下面的内容,2 tes2 0
3 tes3 2
5 tes5 3
6 tes6 3
解决方案 »
- 关于保存记录时自动更新序号的问题,请大家来讨论下
- 请问能否使用T-SQL动态得生成一个access数据库
- 请教一句SQL 只替换第一个出现在字段里的每条记录的字符串 就是文章加TAG功能
- 急, ms sql server 2005 sql server 服务启动不了的问题,见图,在线等
- 删除符合条件的一组记录中的一条?
- 好难的问题呀?有谁来接分呀???
- 如何关闭游标返回的结果集
- 两个记录集(字段相同)能否连接成一个?
- 不用函数,如何用一条SQL语句实现一个功能,SQL高手请进.
- sql语法的检验???给分100,快近来啊!
- SQL Server 报表查询的奇怪问题!请大家帮忙,谢谢!
- MSSQL 2008中date类型的参数如何传给存储过程啊?
with cte as
(
select * from tab where 上级部门编号 = 0
union all
select * from tab join cte on tab.上级部门编号= cte.部门编号
)
select * from cte
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', 4declare @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
*/
select a from test A where b=2
union all
select B.a from cte A ,test B where B.b=A.a
)
select * from cte
create table #t(部门编号 int,部门名称 varchar(10), 上级部门编号 int)insert into #tselect 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', 4with c (部门编号,部门名称,上级部门编号) as
(
select 部门编号,部门名称,上级部门编号 from #t where 部门编号=2
union all
select a.部门编号,a.部门名称,a.上级部门编号 from #t a join c on a.上级部门编号=c.部门编号
)
select *from c2 tes2 0
3 tes3 2
5 tes5 3
6 tes6 3
不好意思,应该是
with cte as
(
select * from tab where 上级部门编号 = 0
union all
select tab.* from tab join cte on tab.上级部门编号= cte.部门编号
)
select * from cte
(
select * from tab where 部门编号 = 2
union all
select tab.* from tab join cte on tab.上级部门编号= cte.部门编号
)
select * from cte
今天上午写的
(
select * from tableName where 部门编号=2
union all
select * from tableName a
join cte t on a.上级部门编号=t.部门编号
)
select * from cte
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
3 tes3 2 0
5 tes5 3 1
6 tes6 3 1