这是简化的表格
filesystem (id, name, parentId);
和一些条目
(1, 'root', NULL)
(2, 'folder', 1)
(3, 'subfolder', 2)
(4, 'subsubfolder', 3)
有没有办法使用原生 SQL 来打印一个条目的绝对路径?
例如,最后一个条目将打印“root/folder/subfolder/subsubfolder”。条目 2 将打印“root/folder”等等。
最佳答案
你可以这样做
with tree(id, Level, Hierarchy) as
(
select id, 0, cast(Name as varchar(max))
from filesystem
union all
select a.id, b.Level+1,
b.Hierarchy+'/'+a.Name
from filesystem a
inner join tree b on a.parentid=b.id
)
select top(1) id, Hierarchy
from tree
where id=4
order by Level desc
它将为您提供带有完整文件路径的 ID。 详细阅读可以check this
关于sql - 如何制作一个sql循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136626/