SQL - 在递归CTE中进行分页,但不是以传统方式进行分页

时间:2016-12-02 15:00:00

标签: sql sql-server tsql recursion common-table-expression

我想应用分页或限制CTE的记录,但不是像通常建议的那样

;WITH children AS
(
    SELECT Item, Parent 
    FROM #TempHeirarchy 
    UNION ALL
    SELECT e.Item, e.Parent  
    FROM #TempHeirarchy e 
    INNER JOIN children e2 
       ON e.Parent = e2.Item
)
select * into #TempFinal
from (select row_number() over(order by parent asc) as RowNumber, * from children) t
where t.RowNumber between 1 and 10

但是这样它首先将递归应用于所有记录,然后应用分页,因此即使我只获取10条记录,也需要花费大量时间。

当CTE解析的记录数达到10条记录时,是否有任何可以完全停止递归的方式?

如果那是不可能的,那么还有其他方法可以生成父子数据并在达到页面大小时停止吗?

2 个答案:

答案 0 :(得分:1)

在递归查询中生成自己的计数器,并在计数10时停止。

此外,您似乎并没有很好地限制您的起始价值。你需要从某个地方开始。

;WITH children AS
(
    SELECT Item, Parent, 0 as cnt 
    FROM #TempHeirarchy 
    WHERE  parent is null --? Missing starting value
    UNION ALL
    SELECT e.Item, e.Parent, cnt+1  
    FROM #TempHeirarchy e 
    INNER JOIN children e2 
       ON e.Parent = e2.Item
    WHERE cnt < 10
)
select * into #TempFinal
from children

答案 1 :(得分:1)

这样的东西?

;WITH children AS
(
    SELECT Item, Parent, 1 as Level
    FROM #TempHeirarchy 
    UNION ALL
    SELECT e.Item, e.Parent, Level+1 as Level
    FROM #TempHeirarchy e 
    INNER JOIN children e2 
       ON e.Parent = e2.Item
    WHERE Level <= 10
)