考虑下面的表格数据:
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
答案 0 :(得分: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