SQL Recursive Query only return the last row

白昼怎懂夜的黑 提交于 2019-12-12 00:27:26

问题


I am trying to get the simple SQL Server 2008 Recursive Query to work.

Following these examples: http://msdn.microsoft.com/en-us/library/ms186243.aspx and SQL Server recursive query

I have a table, with id and parentID:

ID  fParent fName
2   NULL     root   
3    2       Drug_Error 
4    2       Incident   
5    4       2007   
6    4       2009   
7    5       2007-1
8    7       2008-2

with the following query

with recury as (
Select 
fs1.ID ,fs1.FParent,fs1.FName 
from  FoldersStructure as  fs1
where fs1.FParent =null
union all
select fs2.id,fs2.FParent,fs2.FName 
from FoldersStructure as  fs2
inner join recury as r on fs2.FParent= r.ID 
)
select ID,FParent,FName
from recury 
where ID=8

I was hoping to get:

2    null    root
4    2        incident
5    4        2007
7    5        2007-1
8    7        2007-2

But I only get the last one. thanks in advance.


回答1:


Remove the WHERE clause from the statement because it is limiting the resultset to rows where Id = 8. Based on the first comment below, I now understand your requirement! To use 8 as your starting point and to retrieve all parent rows:

WITH recury (Id, ParentId, Name, Level) AS
(
  SELECT fs1.Id ,fs1.ParentId,fs1.Name, CONVERT(int, 0)
  FROM  FoldersStructure AS  fs1
  WHERE fs1.Id = 8
  UNION ALL
  SELECT fs2.Id,fs2.ParentId,fs2.Name, Level - 1
  FROM FoldersStructure AS  fs2
  JOIN recury AS r ON fs2.Id = r.ParentId
)
SELECT Id, ParentId, Name, Level
FROM recury 
ORDER BY  Level;

This code will work if the Ids of the parent rows are not in numeric order. If your parent rows always guaranteed to be in numeric order, you can omit the Level column introduced in the CTE and sort on the Id column instead as per bummi's answer.

SQL fiddle example: http://sqlfiddle.com/#!3/2af0c/4




回答2:


with recury as (
Select 
fs1.ID ,fs1.FParent,fs1.FName 
from  FoldersStructure as  fs1
where fs1.ID=8

union all
select fs2.id,fs2.FParent,fs2.FName 
from FoldersStructure as  fs2
inner join recury as r on fs2.ID= r.FParent

)
select ID,FParent,FName
from recury 
order by ID 

SQL-Fiddle



来源:https://stackoverflow.com/questions/16282702/sql-recursive-query-only-return-the-last-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!