【发布时间】:2014-09-23 01:45:51
【问题描述】:
我有以下 SQL Server CTE 查询:
;with x
as (
select childref, 0 as lvl
from [dbo].[TOMatriX]
where parentref = @parentref
union all
select m.childref, x.lvl+1
from [dbo].[TOMatriX] m
inner join x on m.parentref = x.childref
)
select
lvl [Level],
count(*) [Count],
stuff((select ', ' + CAST(ChildRef AS CHAR(9))
from x t2 where t1.lvl = t2.lvl
for xml path('')),
1,2,'') [Members]
from x t1
group by lvl
我只需要获取最高 12 级的详细信息,因此我将上述查询修改为:
;with x
as (
select childref, 0 as lvl
from [dbo].[TOMatriX]
where parentref = @parentref
union all
select m.childref, x.lvl+1
from [dbo].[TOMatriX] m
inner join x on m.parentref = x.childref
)
select top 12
lvl [Level],
count(*) [Count],
stuff((select ', ' + CAST(ChildRef AS CHAR(9))
from x t2 where t1.lvl = t2.lvl
for xml path('')),
1,2,'') [Members]
from x t1
group by lvl
但是我如何使用 OPTION (maxrecursion) 来打破第 12 级的递归,我无法在我的查询中使用 maxrecursion 选项,我确实尝试如下使用它:
;with x
as (
select childref, 0 as lvl
from [dbo].[TOMatriX]
where parentref = 100000001
union all
select m.childref, x.lvl+1
from [dbo].[TOMatriX] m
inner join x on m.parentref = x.childref
)
select
lvl [Level],
count(*) [Count],
stuff((select ', ' + CAST(ChildRef AS CHAR(9))
from x t2 where t1.lvl = t2.lvl
for xml path('')),
1,2,'') [Members]
from x t1
group by lvl
OPTION (MAXRECURSION 12);
但我收到以下错误:
语句终止。在语句完成之前,最大递归 12 已经用完。
那么,如何使用 OPTION (maxrecursion) 来停止第 12 级的递归,就像在 2nd Query 中使用 TOP 一样。
注意:
的表结构 TABLE [dbo].[TOMatriX](
[ParentRef] [int] NOT NULL,
[ChildRef] [int] NOT NULL,
-- Some Other Columns as well ...
)
如果可能,请提出任何性能改进建议。
【问题讨论】:
-
你不想使用
MAXRECURSION。它会生成错误而不是停止递归。相反,向递归 CTE 添加一个计数器并使用它来停止递归。 -
那么我怎样才能在递归查询上加上 LIMITING CONDITION 呢??
标签: sql sql-server performance recursion common-table-expression