【问题标题】:Breaking a CTE SQL Query on a particular condition在特定条件下中断 CTE SQL 查询
【发布时间】: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


【解决方案1】:

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

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
     )

【讨论】:

  • “选择前 12 名”是否也与“其中 x.lvl
  • @Pratik 。 . .并不真地。你不应该在没有order by 的情况下使用top。您的版本从结果集中返回任意 12 行。
猜你喜欢
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 2016-01-25
相关资源
最近更新 更多