最近做的项目,遇到如下问题:我有一个表:Dept  简单举例如下
ID, Name, ParentId
1   a     0
2   b     1
3   c     1
4   d     1
5   b01   2
6   b0101 5
7   c01   3
8   c0101 7
9   d01   4
10  d0101 9还有一个Msg 表,其中有个字段是Varchar类型 存储的是有权限看的部门ID
如下
ID  Name  Depts
1   msg   2,4
2   msg   3我有一个Staffer 表
其中有个Dept字段是Staffer对应的部门
现在我要做个查询,
就是查询某个Staffer对应的Msg表意思就是Msg里面存储的部门,只要Staffer的Dept字段是其或是其
子部门(子子部门...递归)就有权限,如staffer 对应 dept 为6,
那么Msg 中字段只要包含1,2,5,6(即dept为6的父部门--祖部门的 都可以查看到这样的查询语句我该怎么写?请教高手

解决方案 »

  1.   

    ----感觉就是取一个部门所有的父
    declare @i int
    set @i=1 declare @r table(id int,deep int)---取出ID为6的所有父
    insert into @r(id,deep)
    select ParentId, @i from Deptwhile (@@rowcount>0)
    begin
    set @i=@i+1 insert into @r(id,deep)
    select ParentId, @i from Dept a
    inner join @r b where b.id=a.id
    where b.deep=@i-1
    end
      

  2.   

    給出些Staffer 表的數據,以及你最好要得到的結果是怎樣的。
      

  3.   

    我的Staffer 与之相关的是如下结构
    ID   Name      Deptid
    1     aaa        5
    2     bbb        6
    3     ccc        9我要进行一个查询 查询Staffer可以查看的所有Msg只要Msg里的字段包含staffer.deptid的部门以及根部门,staffer就有权查看.如staffer.deptid 为6的时候1,2,5,6 都是6的根部门或者自身只要msg表里的depts字段包含这4个数,staffer都可以查询出来
      

  4.   

    象上面的数据staffer.deptid 为6时,Msg表的第一项包含了2,那么就满足条件
      

  5.   

    create table dept(id int,name varchar(10),parentid int)
    insert dept
    select 1,'a',0 union all
    select 2,'b',1 union all
    select 3,'c',1 union all
    select 4,'d',1 union all
    select 5,'b01',2 union all
    select 6,'b0101',5 union all
    select 7,'c01',3 union all
    select 8,'c0101',7 union all
    select 9,'d01',4 union all
    select 10,'d0101',9 
    create table msg(id int,name varchar(10),depts varchar(200))
    insert msg
    select 1,'msg','2,4' union
    select 2,'msg','3'go
    create function dbo.f_tb(@id int)
    returns @tb table(id int,pid int,levels int)
    as
    begin
    declare @i int
    set @i=0
    insert into @tb 
    select ID,ParentId,@i from Dept where id=@id
    while @@rowcount>0
    begin
    set @i=@i+1
    insert into @tb 
    select a.ID,a.ParentId,@i from Dept a,@tb b where a.id=b.pid and levels=@i-1
    end
    return
    end
    go
    select * from msg a where exists(
    select 1 from dbo.f_tb(6) where charindex(','+cast(id as varchar)+',',','+a.Depts+',')>0
    )
    drop table msg,dept
    drop function dbo.f_tb
      

  6.   

    如staffer.deptid 为6的时候
    ===对应:参数6,dbo.f_tb(6)