拥有自我引用关系的数据

时间:2014-03-03 07:13:11

标签: tsql

我有这样的树

Folder0
|
|__Folder1
|  |
|  |_______Folder2
|  |        |_______Folder3
|  |        |_______Folder4
|  |_______Folder5
|  |_______Folder6
|__Folder7

表的字段类似于Id,fld_Id,Name,其中fld_Id是文件夹的父ID

 Id    ,    fld_Id     ,   Name
________________________________
 1           Null          Folder0
 2           Null          Folder7
 3            1            Folder1
 4            3            Folder2
 5            4            Folder3
 6            4            Folder4
 7            3            Folder5
 7            3            Folder6

如何获取位于Folder1下的所有目录的列表 这将是

 Id    ,    fld_Id     ,   Name
________________________________
 3            1            Folder1
 4            3            Folder2
 5            4            Folder3
 6            4            Folder4
 7            3            Folder5
 7            3            Folder6

1 个答案:

答案 0 :(得分:0)

尝试使用如下的递归CTE:

;with CTE as
(
   SELECT  Id,fld_Id,Name FROM Test t1 WHERE Id = 3

   UNION ALL

   SELECT  t1.Id, t1.fld_Id, t1.Name
   FROM Test t1
   INNER JOIN CTE ON t1.fld_Id = CTE.Id
)

SELECT * FROM CTE order by Id

<强> SQL Fiddle Demo