带OPTION的无限循环CTE(maxrecursion 0)
我有CTE查询与大logging。 以前它工作正常。 但是最近呢,这对一些会员来说是个错误
声明终止。 报表完成前,最大recursion100已经耗尽。
所以我把OPTION (maxrecursion 0)
或OPTION (maxrecursion 32767)
放在我的查询上,因为我不想限制logging。 但是,结果是查询需要永久加载。 我如何解决这个问题?
这是我的代码:
with cte as( -- Anchor member definition SELECT e.SponsorMemberID , e.MemberID, 1 AS Level FROM tblMember AS e where e.memberid = @MemberID union all -- Recursive member definition select child.SponsorMemberID , child.MemberID, Level + 1 from tblMember child join cte parent on parent.MemberID = child.SponsorMemberID ) -- Select the CTE result Select distinct a.* from cte a option (maxrecursion 0)
编辑:删除不必要的代码,以便于理解
解决:所以这个问题不是来自maxrecursion
。 来自CTE。 我不知道为什么,但可能它包含任何赞助商周期:A – > B – > C – > A – > …(感谢@HABO)
我试过这种方法,它的工作原理。 在parsing自引用表时,CTE中的无限循环
如果您正在达到recursion限制,您可能在赞助关系或数据循环方面拥有相当深的层次。 像下面这样的查询将检测循环并终止recursion:
declare @tblMember as Table ( MemberId Int, SponsorMemberId Int ); insert into @tblMember ( MemberId, SponsorMemberId ) values ( 1, 2 ), ( 2, 3 ), ( 3, 5 ), ( 4, 5 ), ( 5, 1 ), ( 3, 3 ); declare @MemberId as Int = 3; declare @False as Bit = 0, @True as Bit = 1; with Children as ( select MemberId, SponsorMemberId, Convert( VarChar(4096), '>' + Convert( VarChar(10), MemberId ) + '>' ) as Path, @False as Loop from @tblMember where MemberId = @MemberId union all select Child.MemberId, Child.SponsorMemberId, Convert( VarChar(4096), Path + Convert( VarChar(10), Child.MemberId ) + '>' ), case when CharIndex( '>' + Convert( VarChar(10), Child.MemberId ) + '>', Path ) = 0 then @False else @True end from @tblMember as Child inner join Children as Parent on Parent.MemberId = Child.SponsorMemberId where Parent.Loop = 0 ) select * from Children option ( MaxRecursion 0 );