路径枚举模型,如何获得上级?

问题描述

| 考虑以下表格数据:
emp_name VARCHAR(25),path VARCHAR(150)
Albert                /Albert
John                  /Albert/John
Chuck                 /Albert/Chuck
Tom                   /Albert/John/Tom
Frank                 /Frank
我想获得汤姆上司的名单:
John
Albert
(可以包括汤姆) 是否可以在不拆分路径的情况下使用序列表(仅是我发现的方式)来完成? DB是sql Server 2008 R2     

解决方法

您可以使用递归CTE拆分层次结构字符串值。
declare @T table 
(
  ID int identity,emp_name varchar(25),[path] varchar(150)
)

insert into @T values
(\'Albert\',\'Albert\'),(\'John\',\'Albert/John\'),(\'Chuck\',\'Albert/Chuck\'),(\'Tom\',\'Albert/John/Tom\'),(\'Frank\',\'Frank\')

declare @EmpName varchar(25) = \'Tom\'

;with cte(Sort,P1,P2,[path]) as
(
  select 1,1,charindex(\'/\',[path]+\'/\',1),[path]
  from @T
  where emp_name = @EmpName  
  union all
  select Sort+1,P2+1,C.P2+1),[path]
  from cte as C
  where charindex(\'/\',C.P2+1) > 0
)
select substring([path],P2-P1)
from cte
order by Sort
结果:
(No column name)
Albert
John
Tom
在此处测试查询:http://data.stackexchange.com/stackoverflow/q/101383/ 您可以尝试的另一件事
select T2.emp_name
from @T as T1
  inner join @T as T2
    on \'/\'+T1.[path]+\'/\' like \'%/\'+T2.emp_name+\'/%\' and
       T2.emp_name <> @EmpName  
where T1.emp_name = @EmpName
http://data.stackexchange.com/stackoverflow/q/101518/get-hierarchy-with-join-using-like