這裏有一個遞歸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;
對不起,我應該更清楚。我需要從錨點攜帶屬性字段,而不是一個常量值。您的解決方案適用於固定值。 – ScrewWorkn
作爲一個例子,常數必須由您需要的列替換,因爲您沒有提供更多信息。但似乎查詢是不能工作,因爲's'沒有定義子句是'lcte.Me = link.Parent' –
謝謝,我實際上已經嘗試過這個想法後,你給你的第一個,它沒有工作,儘管今天工作,所以我一定做錯了什麼。 – ScrewWorkn