语句完成前已用尽最大递归100


136

我不断得到max recursion error这个查询。

起初我以为是因为返回了null,然后它会尝试与null值匹配,从而导致错误,但是,我重写了查询,因此不返回null并仍然发生错误。

什么是重写此功能的最佳方法,这样就不会发生错误

WITH EmployeeTree AS
(
    SELECT 
        EMP_SRC_ID_NR Id, USR_ACV_DIR_ID_TE Uuid, 
        CASE Employees.APV_MGR_EMP_ID 
           WHEN Null THEN '0' 
           ELSE Employees.APV_MGR_EMP_ID 
        END as  ApprovalManagerId 
    FROM 
        dbo.[tEmployees] as Employees WITH (NOLOCK)
    WHERE 
        APV_MGR_EMP_ID = @Id 
        and Employees.APV_MGR_EMP_ID is not null 
        and Employees.EMP_SRC_ID_NR is not null  

    UNION ALL

    SELECT 
        EMP_SRC_ID_NR Id, USR_ACV_DIR_ID_TE Uuid, 
        CASE Employees.UPS_ACP_EMP_NR 
           WHEN Null THEN '1' 
           ELSE Employees.UPS_ACP_EMP_NR 
        END as ApprovalManagerId 
    FROM 
        dbo.[tEmployees] as Employees WITH (NOLOCK)
    WHERE 
        UPS_ACP_EMP_NR = @Id 
        and Employees.APV_MGR_EMP_ID is not null 
        and Employees.EMP_SRC_ID_NR is not null  

    UNION ALL

    SELECT 
        Employees.EMP_SRC_ID_NR, Employees.USR_ACV_DIR_ID_TE, 
        CASE Employees.APV_MGR_EMP_ID 
            WHEN Null THEN '2' 
            ELSE Employees.APV_MGR_EMP_ID 
        END  
    FROM 
        dbo.[tEmployees] as Employees WITH (NOLOCK)
    JOIN 
        EmployeeTree ON Employees.APV_MGR_EMP_ID = EmployeeTree.Id 
    where  
        Employees.APV_MGR_EMP_ID is not null 
        and Employees.EMP_SRC_ID_NR is not null             
)
SELECT 
    Id AS [EmployeeId], 
    Uuid AS [EmployeeUuid], 
    ApprovalManagerId AS [ManagerId] 
FROM EmployeeTree        

此行可以替换为COALESCE()CASE Employees.APV_MGR_EMP_ID WHEN Null THEN '0' ELSE Employees.APV_MGR_EMP_ID END as ApprovalManagerId=COALESCE(Employees.APV_MGR_EMP_ID, 0) AS ApprovalManagerID
David Faber

Answers:


249

在查询末尾指定maxrecursion选项

...
from EmployeeTree
option (maxrecursion 0)

这样,您可以指定CTE在产生错误之前可以递归的频率。Maxrecursion 0允许无限递归。


1
嗯,这
行得通,

5
@bugz Maxrecursion 0现在确实会影响您的查询,您是否需要在其他地方查找问题
t-clausen.dk 2012年

6
嗯,这是我数据中的循环
引用

3
+1我使用此选项来调试类似的问题。如果查询是无限递归的,则在执行查询后必须在Management Studio中取消该查询,否则服务器将假脱机执行行,直到客户端内存不足。
Iain Samuel McLean年长者,

1
虽然这可能在您希望查询进行很深的递归的情况下解决了该问题,但它可能只是掩盖了查询中的问题。
Christian Findlay'7

24

它只是避免最大递归误差的示例。我们必须使用选项(maxrecursion 365); 或选项(最大递归0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.