2016-10-12 109 views
1
FromID    ToID  
-------------- ----------  
    1    2    
    2    3     
    3    4     
    5    6     
    6    7     
    9    10 

我想用在SQL Server 2008中递归查询创建一个输出作为SQL Server 2008的递归查询

FromID    Path 
1      1,2,3,4 
5      5,6,7           
9      9,10 

我一直在努力构建一个SQL语句中使用参照网上的例子如下

;WITH items AS (
    SELECT FromID 
    , CAST(FromID AS VARCHAR(255)) AS Path 
    FROM tablex 
    UNION ALL 
    SELECT i.FromID 
    , CAST(Path + '.' + CAST(i.FromID AS VARCHAR(255)) AS VARCHAR(255)) AS Path 
    FROM tablex i 
    INNER JOIN items itms ON itms.FromID = i.ToID 
) 
SELECT * 
FROM items 
ORDER BY Path 

但是,上述不起作用。有任何想法吗?

+0

所以2-3将不获得自己的行,但6-9会因为你有6-7以前? –

+0

嗨,为了简化,我已经拿出6-9。它就像一棵树结构,其中1,5,9是根ID。我需要每个根的孩子ID – user3050151

回答

1

为什么你的预期输出是它是什么它不是完全清楚给我。从6-10的路径不是10的完整路径:该路径始于ID 5.我已经写了输出的完整路径,说明你会如何去这样做的例子。如果你确实希望它由于某种原因从6开始,那么请清楚地说明确定哪些节点应该作为结果集中的起点出现的规则。

我注意到,在您的样本数据中的每个ID只能有一个前身,但潜在的多个接班人。出于这个原因,我选择从识别端点节点开始,然后回溯到起点。希望下面的代码注释足以解释正在发生的其他事情。

declare @TableX table (FromID int, ToID int); 
insert @TableX values (1, 2), (2, 3), (3, 4), (5, 6), (6, 7), (6, 9), (9, 10); 

with PathCTE as 
(
    -- BASE CASE 
    -- Any ID that appears as a "to" but not a "from" is the endpoint of a path. This 
    -- query captures the ID that leads directly to that endpoint, plus the path 
    -- represented by that one row in the table. 
    select 
     X1.FromID, 
     [Path] = convert(varchar(max), X1.FromID) + ',' + convert(varchar(max), X1.ToID) 
    from 
     @TableX X1 
    where 
     not exists (select 1 from @TableX X2 where X2.FromID = X1.ToID) 

    union all 

    -- RECURSIVE CASE 
    -- For every path previously identified, look for another record in @TableX that 
    -- leads to its starting point and prepend that record's from ID to the overall path. 
    select 
     X.FromID, 
     [Path] = convert(varchar(max), X.FromID) + ',' + PathCTE.[Path] 
    from 
     PathCTE 
     inner join @TableX X on PathCTE.FromID = X.ToID 
) 

-- Any ID that appears as a "from" but not a "to" is the starting point of one or more 
-- paths, so we get all results beginning at one of those points. All other output from 
-- PathCTE is partial paths, which we can ignore. 
select * 
from 
    PathCTE 
where 
    not exists (select 1 from @TableX X where PathCTE.FromID = X.ToID) 
order by 
    FromID, [Path]; 

输出:

FromID Path 
1  1,2,3,4 
5  5,6,7 
5  5,6,9,10 
+0

嗨,谢谢。我试图简化我的问题。我其实有两张桌子。第二个表包含每个节点的坐标。例如记录1-coords1,2-coords2,3-coords3,4-coords4等。我还需要加入2个表格,以便最终得到一个输出,其中字段'Path'返回坐标 – user3050151

+0

@ user3050151:这听起来应该只是对上面查询中CTE内部的两个'select'语句的简单修改。修改每个'from'子句以从'@ TableX'连接到第二个表,然后修改'[Path]'的定义以使用第二个表中相应的字段替代'X.FromID'。 –