表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部门下的所有下级部门的人员,如:
点广东公司,能把广州和深圳分公司的人员都查找出来.
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部门下的所有下级部门的人员,如:
点广东公司,能把广州和深圳分公司的人员都查找出来.
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,'周星星')
godeclare @dept_id as int
set @dept_id = 1select 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 行)
*/
(
@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
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
GOselect * from 人员表STAFF order by dbo.uf_getpath(staff_dept)
->
select @ID = super_dept_id from 表DEPT where dept_id = @parentID
如:广东分公司dept_id=2
首先从部门表中super_dept_ID=2的ID号得到下属部门ID号3和4.然后组成2.3.4,最后,在STAFF中搜索staff_dept为2.3.4的人员