[英]Recursive query in SQL Server 2008
I have this table 我有这张桌子
MyTable MyTable的
rowNew rowOld
1 ------- 2
2 ------- 3
3 ------- 4
4 ------- 5
7 ------- 8
8 ------- 9
I want to select query like this: 我想选择这样的查询:
rowNew rowOld
1 ------- 2
2 ------- 3
3 ------- 4
4 ------- 5
i wrote this with cte 我用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
and I got this records: 我得到了以下记录:
rowNew rowOld
1 ------- 2
1 ------- 2
1 ------- 2
1 ------- 2
what is he problem? 他怎么了
You put your where
condition in the wrong spot - it should be in the anchor query in the CTE definition to limit your starting point. 您将
where
条件放在错误的位置-它应该在CTE定义的锚查询中,以限制您的起点。
Also, you have join condition the other way round if you want to define parent-child relationship. 另外,如果要定义父子关系,则具有相反的加入条件。
It all should be: 这应该是:
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.