2017-04-12 46 views
2

我有一個cte,只是循環通過一個表通過子/父母關係鏈接到自己。我有一個種子查詢,我想從種子查詢中攜帶一個值到它的所有後代,以便所有行都知道它來自哪個種子。任何方式來做到這一點?評論後SQL CTE - >通過從錨到所有行攜帶一個值

WITH cte 
AS  (select Me, MyParent, Attribute 
     from MyTable 
     where 
     Attribute in 
      (
      847 
      ,1011 
      ,1019 
      ) 
     UNION ALL 
     SELECT Link.Me, Link.Parent, Link.Attribute 
     FROM cte 
      JOIN LINK ON cte.Me = S.Parent   
     ) 

回答

1
WITH cte 
AS  (
    select Me, MyParent, Attribute, 'valueToCarry' value_to_Carry 
    from MyTable 
    where 
    Attribute in 
     (
     847 
     ,1011 
     ,1019 
     ) 
    UNION ALL 
    SELECT Link.Me, Link.Parent, Link.Attribute, cte.value_to_carry 
    FROM cte 
     JOIN LINK ON cte.Me = S.Parent   
) 

編輯:

WITH cte 
AS  (
    select Me, MyParent, Attribute, Attribute RootAttr 
    from MyTable 
    where 
    Attribute in 
     (
     847 
     ,1011 
     ,1019 
     ) 
    UNION ALL 
    SELECT Link.Me, Link.Parent, Link.Attribute, cte.RootAttr 
    FROM cte 
     JOIN LINK ON cte.Me = S.Parent   
) 
+0

對不起,我應該更清楚。我需要從錨點攜帶屬性字段,而不是一個常量值。您的解決方案適用於固定值。 – ScrewWorkn

+0

作爲一個例子,常數必須由您需要的列替換,因爲您沒有提供更多信息。但似乎查詢是不能工作,因爲's'沒有定義子句是'lcte.Me = link.Parent' –

+0

謝謝,我實際上已經嘗試過這個想法後,你給你的第一個,它沒有工作,儘管今天工作,所以我一定做錯了什麼。 – ScrewWorkn

0

這裏有一個遞歸CTE的SQL Server上工作的一個例子。
您基本上將cte中的值傳遞給cte中的第二個查詢。
它被稱爲遞歸,因爲cte自己調用它,這使得它遍歷所有的父母,直到沒有父母可以被鏈接了。

-- using a table variable, cos it's a demonstration 
declare @MyTable table (Child int, Parent int, Attribute int); 

insert into @MyTable (Child, Parent, Attribute) values 
(1,2,847), 
(1,3,847), 
(2,0,1011), 
(3,4,1019), 
(4,0,1019); 

WITH CTE 
AS (
    -- the seed records, where the cte starts 
    select 
    Child, Parent, Attribute, 
    Child as RootChild, Attribute as RootAttribute, 0 as PreviousChild, 0 as Level 
    from @MyTable 
    where Attribute in (847, 1011, 1019) 

    union all 

    -- the records linked to the previously new records in the CTE 
    SELECT 
    link.Child, link.Parent, link.Attribute, 
    -- we also take fields from the cte to get the previous data that was put in the resultset of the cte 
    cte.RootChild, cte.RootAttribute, cte.Child as PreviousChild, cte.Level + 1 as Level 
    FROM cte 
    JOIN @MyTable link ON (cte.Parent = link.Child) 
) 
select * from cte 
order by RootChild, Level; 

-- This time we link to the link.Parent which will give different results 
WITH CTE 
AS (
    select 
    Parent, Child, Attribute, 
    Parent as RootParent, Attribute as RootAttribute, 0 as PreviousParent, 0 as Level 
    from @MyTable 
    where Attribute in (847, 1011, 1019) 

    union all 

    SELECT 
    link.Parent, link.Child, link.Attribute, 
    cte.RootParent, cte.RootAttribute, cte.Parent as PreviousParent, cte.Level + 1 as Level 
    FROM cte 
    JOIN @MyTable link ON (cte.Child = link.Parent) 
) 
select * from cte 
order by RootParent, Level;