当前位置: 代码迷 >> Sql Server >> 请问一个小疑点,怎么搜索下级部门的人员
  详细解决方案

请问一个小疑点,怎么搜索下级部门的人员

热度:127   发布时间:2016-04-27 19:36:19.0
请教一个小问题,如何搜索下级部门的人员?
表DEPT
dept_id   super_dept_id(父部门)   dept_id
      1                     0                                     总公司
      2                     1                                     广东公司
      3                     2                                     广州分公司
      4                     2                                     深圳分公司
----
表:人员表STAFF
staff_id   staff_dept     staff_name
      1                     3                     刘德华
      2                     4                     张靓影
      3                     2                     周星星
...
在存储过程中,如何搜索到X部门下的所有下级部门的人员,如:
点广东公司,能把广州和深圳分公司的人员都查找出来.

------解决方案--------------------
create table A(dept_id int,super_dept_id int ,dept_name varchar(10))
insert into A values(1,0, '总公司 ')
insert into A values(2,1, '广东公司 ')
insert into A values(3,2, '广州分公司 ')
insert into A values(4,2, '深圳分公司 ')
create table B(staff_id int,staff_dept int, staff_name varchar(10))
insert into B values(1,3, '刘德华 ')
insert into B values(2,4, '张靓影 ')
insert into B values(3,2, '周星星 ')
go

declare @dept_id as int
set @dept_id = 1

select B.* from B where staff_dept in
(
Select A.dept_id from A where super_dept_id = @dept_id
union all
select A.dept_id from A where super_dept_id in (Select A.dept_id from A where super_dept_id = @dept_id)
)

drop table A,B

/*
staff_id staff_dept staff_name
----------- ----------- ----------
1 3 刘德华
2 4 张靓影
3 2 周星星

(所影响的行数为 3 行)
*/

------解决方案--------------------
Create proc [dbo].[Get]
(
@Part int)
as
begin
select staff_name from STAFF join left DEPT where DEPT.super_dept_id> @Part or [email protected]
end

------解决方案--------------------
dept_id super_dept_id(父部门) dept_id
1 0 总公司
2 1 广东公司
3 2 广州分公司
4 2

create function dbo.uf_getpath(@parentID int)
returns varchar(1000)
as
begin
declare @s varchar(1000),@id varchar(64)
set @s = ' '
select @ID = super_dept_id from test where dept_id = @parentID
while @@rowcount > 0 and @ID <> 0
begin
set @s = @s+rtrim(reverse(@ID))
  相关解决方案