【问题标题】:hierarchy query sql server 2008层次查询sql server 2008
【发布时间】:2012-10-13 16:37:13
【问题描述】:
EmployeeId, Name, ManagerId
1,Mac Manager, null
2,Sue Supervisor, 1
3,Earl Employee, 2
4,Sam Supervisor, 1
5,Ella Employee, 4

Given: Employee Id = 3

你能帮我用 sql 让员工和经理上链吗?

在这个例子中,结果是

Earl
Sue
Mac

【问题讨论】:

    标签: sql-server-2008


    【解决方案1】:

    看看Recursive Queries Using Common Table Expressions

    declare @EmpID int = 3;
    
    with C as
    (
      select E.EmployeeId,
             E.Name,
             E.ManagerId
      from YourTable as E
      where E.EmployeeId = @EmpID
      union all
      select E.EmployeeId,
             E.Name,
             E.ManagerId
      from YourTable as E
        inner join C  
          on E.EmployeeId = C.ManagerId
    )
    select C.Name
    from C
    

    SE-Data

    【讨论】:

      【解决方案2】:
      declare @current int 
      set @current = @empid
      while @current is not null begin
      
         -- do something with it
         print @current
      
         set @current = (select ManagerId from table where EmployeeId = @current)
      end
      

      【讨论】:

        猜你喜欢
        • 2011-11-20
        • 1970-01-01
        • 2015-11-23
        • 2011-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多