--建立環境 
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