[英]Recursive query in SQL Server 2008
我有這張桌子
MyTable的
rowNew rowOld
1 ------- 2
2 ------- 3
3 ------- 4
4 ------- 5
7 ------- 8
8 ------- 9
我想選擇這樣的查詢:
rowNew rowOld
1 ------- 2
2 ------- 3
3 ------- 4
4 ------- 5
我用CTE寫的
with cte(rowNew, rowOld)
as
(
select rowNew, rowOld from MyTable
union all
select rowNew, rowOld from MyTable
inner join cte on MyTable.rowOld = cte.rowNew
)
select rowNew, rowOld from cte
where cte.rowNew = 1
我得到了以下記錄:
rowNew rowOld
1 ------- 2
1 ------- 2
1 ------- 2
1 ------- 2
他怎么了
您將where
條件放在錯誤的位置-它應該在CTE定義的錨查詢中,以限制您的起點。
另外,如果要定義父子關系,則具有相反的加入條件。
這應該是:
with cte(rowNew, rowOld)
as
(
select rowNew, rowOld from MyTable
where rowNew = 1
union all
select MyTable.rowNew, MyTable.rowOld from MyTable
inner join cte on MyTable.rowNew = cte.rowOld
)
select rowNew, rowOld from cte
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.