当前位置:编程学习 > C#/ASP.NET >>

关于SQL里面的一个递归查询的问题

  假设我现在有有三个部门,市场部,市场一部,市场二部,其中市场一部是市场部下的一个部门,市场二部又是市场一部下面的一个部门,现在我是市场部的管理员,我要查询出所有属于市场部的部门的员工信息来,要怎么弄,求代码,或者有类似功能的代码也可以,多谢了
   --------------------编程问答-------------------- 递归查询还真没用过。。 --------------------编程问答-------------------- 不知道为什么你要用递归、
我以前也没用过,刚才百度了一下 希望可以帮到你

create procedure GetData(@a nvarchar(50))
as
begin
 create table #Temp(
  a nvarchar(50),
  b nvarchar(50),
  c nvarchar(50)
 )

 declare @tempB nvarchar(50)

 insert into #Temp select a,b,c from T where a in(@a)

 declare cur cursor for select b from #Temp
 open cur
 fetch next from cur into @tempB
 while @@fetch_status = 0
 begin
  insert into #Temp select a,b,c from T where a in(@tempB)
  fetch next from cur into @tempB
 end
 close cur
 deallocate cur

 select * from #Temp
end

=====================================================
上面的是假设表结构如下的:
a        b        c
=========================
1 2 aa
1 3 dfd
2 4 fdas
3 5 fds
4 7 fds


exec GetData '2'
返回
a        b        c
2 4 fdas
4 7 fds --------------------编程问答--------------------
create table #Department(id int,name varchar(50),pid int)
insert into #Department
select 1,'市场部',0 union all
select 2,'市场一部',1 union all
select 3,'市场二部',2 union all 
select 4,'其他部',0

declare @name varchar(50)
set @name='市场部'
;with cte as(
select id,[name],pid from #Department where [name]=@name
union all
select d.id,d.[name],d.pid from #Department d inner join cte on cte.id=d.pid
)
select * from cte
--------------------编程问答--------------------
引用 3 楼 huangwenquan123 的回复:
SQL code

create table #Department(id int,name varchar(50),pid int)
insert into #Department
select 1,'市场部',0 union all
select 2,'市场一部',1 union all
select 3,'市场二部',2 union all 
select 4,'其他部',0
……




好像有问题代码 --------------------编程问答-------------------- 不知道你数据库里现在的表和数据的情况
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,