2011-05-26 14 views
1

考慮下面的表中的數據:路徑枚舉模型,如何取得上級?

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

回答

1

您可以使用遞歸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, 
     charindex('/', [path]+'/', C.P2+1), 
     [path] 
    from cte as C 
    where charindex('/', [path]+'/', C.P2+1) > 0 
) 
select substring([path], P1, 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

+0

是否有可能做這不使用遞歸方法? – user666423 2011-05-26 17:12:41

+0

@user - 好的。正如你所說的使用序列表。你爲什麼不想使用遞歸CTE?它是否對你有性能問題?你也可以使用字符串分割功能。在SO上發佈了一系列它們。 – 2011-05-26 17:21:03

+0

在哪裏(鏈接)?我試圖只用序列表來做,但無法弄清楚。 – user666423 2011-05-26 18:19:07