在特定条件下中断CTE SQL查询

时间:2014-09-23 01:45:51

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

我有以下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级停止递归,就像在第二次查询中使用TOP一样。

注意:

的表格结构
    TABLE [dbo].[TOMatriX](

        [ParentRef] [int] NOT NULL,
        [ChildRef] [int] NOT NULL,
-- Some Other Columns as well ...

)

如果可能,请建议任何性能改进。

1 个答案:

答案 0 :(得分:2)

以下是您如何设置限制条件的示例:

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
      where x.lvl <= 12
     )