日期:2014-05-18  浏览次数:20466 次

我不知道已得得到的部门如何与员工表连接.
--建立環境 
create table company (dept_id int, super_dept_id int, dept_name varchar(20)) 
insert into company 
select 1, 0, '中国公司 '  
union all select 2, 1, '北京分公司 '  
union all select 3, 1, '广东分公司 '  
union all select 4, 2, '北京东城区分公司 '  
union all select 5, 2, '北京海淀区分公司 '  
union all select 6, 3, ' 广东广州分公司 '  
union all select 7, 3, '广东深圳分公司 '  

---建立函數 

create function fnGetChildren(@id int) 
returns @tmp table(dept_id int,dept_name varchar(20)) 
as 
begin 
  insert @tmp select dept_id,dept_name from company where dept_id = @id 
  while @@rowcount > 0 
  insert @tmp select a.dept_id,a.dept_name from company as a INNER JOIN @tmp as b 
  on a.super_dept_id = b.dept_id where a.dept_id not in(select dept_id from @tmp) 
return 
end 


  
--測試: 
  
select * from dbo.fnGetChildren(2)  


/* 
結果: 

dept_id dept_name 
---------------------------------------------------- 
2 北京分公司 
4 北京东城区分公司 
5 北京海淀区分公司 
*/ 

我不知道如何与员工表连接.我要得到下属部门的所有员工信息
员工表staff
staff_id staff_dept staff_name


------解决方案--------------------
员工表和部门表哪两个字段是关联的?
------解决方案--------------------
假如STAFF_DEPT是关联的
select * from dbo.fnGetChildren(2) F INNER JOIN STAFF G ON G.STAFF_DEPT=F.DEPT_ID
------解决方案--------------------

select staff_id,staff_name,dept_name from fnGetChildren(3) as a,[Stuff] as b where a.dept_id=b.staff_dept