0

我有以下SQL Server CTE查詢:在特定條件下打破的CTE SQL查詢

;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 ... 

) 

如果可能的話,請諮詢任何性能改進爲好。

+0

你不想使用'MAXRECURSION'。它會產生一個錯誤,而不是停止遞歸。相反,向遞歸CTE添加一個計數器並使用它來停止遞歸。 – 2014-09-23 01:50:14

+0

那麼我怎樣才能把遞歸查詢的限制條件? – Pratik 2014-09-23 01:51:46

回答

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 
    ) 
+0

「select top 12」是否也以與「where x.lvl <= 12?」相同的方式工作? – Pratik 2014-09-23 02:25:00

+0

@Pratik。 。 。不是真的。如果沒有'order by'命令,你不應該使用'top'。您的版本從結果集中返回任意12行。 – 2014-09-23 03:05:01