读书人

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

发布时间: 2012-01-12 22:11:58 作者: rapoo

请教一个小问题,如何搜索下级部门的人员?
表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 DEPT.super_dept_id=@Part
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))


select @ID = super_dept_id from 表DEPT where dept_id = @ID
end
return reverse(@s)+rtrim(@parentID)
end
GO

select * from 人员表STAFF order by dbo.uf_getpath(staff_dept)

读书人网 >SQL Server

热点推荐