问题描述:
    表id pid saleid 其中id为当前登录人 pid为当前登录人的上级领导 saleid销售员id
    实现 在一个视图中查出所有saleid1,saleid2(saleid1为当前登录人的,saleid2为当前登录人以及其下级的)通过该视图根据当前登录人可以看到自己以及所有下级(包括下下级......)saleid
    调用视图时根据当前登录人的saleid=saleid1可以看到自己以及所有下级的saleid2,例如当前登录人是最底层一级的,则他只能看到自己的saleid2,若当前登录人为销售经理则可以看到他下面的所有销售主管以及所有销售主管下的销售人员的saleid2,如登录人是总经理,则可以看到所有的saleid2

解决方案 »

  1.   

    create table tb(id int,pid int,saleid int)
    insert into tb select 1,null,2
    insert into tb select 2,1,3
    insert into tb select 2,1,4
    insert into tb select 3,2,5
    insert into tb select 4,2,6
    go
    declare @id int
    set @id=2
    ;with cte as(
    select @id as id
    union all
    select b.saleid from tb b inner join cte a on b.id=a.id
    )select distinct * from cte
    go
    drop table tb
    /*
    --@id=2
    id
    -----------
    2
    3
    4
    5
    6(5 行受影响)
    --其他的楼主自己去试.2005中适用
    */
      

  2.   


    declare @table table (id int ,pid int ,saleid int)
    insert into @table
    select 1,0,4 union all
    select 2,1,5 union all
    select 3,1,6 union all
    select 4,2,7 union all
    select 5,3,8 union all
    select 6,4,9 union all
    select 7,5,10 union all
    select 8,0,11;WITH    Maco
              AS ( SELECT   id ,
                            pid,
                            saleid
                   FROM     @table
                   WHERE    id = 1
                   UNION ALL
                   SELECT   a.id ,
                            a.pid,
                            a.saleid
                   FROM     @table AS a ,
                            Maco AS b
                   WHERE    a.pid = b.id
                 )
        SELECT  *
        FROM    Maco order by id
    /*
    id          pid         saleid
    ----------- ----------- -----------
    1           0           4
    2           1           5
    3           1           6
    4           2           7
    5           3           8
    6           4           9
    7           5           10
    */