명령문 완료 전에 최대 재귀 100이 소진되었습니다. WHEN Null THEN ‘1’

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        


답변

쿼리 끝에 maxrecursion 옵션 을 지정하십시오 .

...
from EmployeeTree
option (maxrecursion 0)

이를 통해 오류를 생성하기 전에 CTE가 얼마나 자주 재귀 할 수 있는지 지정할 수 있습니다. Maxrecursion 0은 무한 재귀를 허용합니다.


답변

최대 재귀 오류를 피하기위한 샘플 일뿐입니다. 옵션 (maxrecursion 365) 을 사용해야합니다 . 또는 옵션 (maxrecursion 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);