How to set the maxrecursion option for a CTE inside a Table-Valued-Function

后端 未结 6 1548
粉色の甜心
粉色の甜心 2020-11-29 08:01

I\'m facing a problem declaring the maxrecursion option for a CTE inside a TVF.

Here is the CTE (a simple calendar):

DECLARE @DEBUT DATE = \'1/1/11\'         


        
6条回答
  •  忘掉有多难
    2020-11-29 08:26

    Another way to handle this is to break up the problem into a pair of CTEs, neither of which hits the recursion limit of 100. The first CTE creates a list with the begin date for each month in the range. The second CTE then fills in all the days of each month. As long as the input range is fewer than 100 months, it should work fine. If an input range of greater than 100 months is required, the same idea could be expanded with a third CTE for years added ahead of the months CTE.

    CREATE FUNCTION [liste_jour]    
    (@debut datetime, @fin datetime)    
    RETURNS TABLE   
    AS      
    RETURN          
    (   
        WITH CTE_MOIS AS
        (           
            SELECT JOUR_DEBUT = @debut
            UNION ALL
            SELECT DATEADD(MONTH, 1, CTE_MOIS.JOUR_DEBUT)
              FROM CTE_MOIS         
             WHERE DATEADD(MONTH, 1, CTE_MOIS.JOUR_DEBUT) <= @fin
        ),
    
        CTE_JOUR AS
        (           
            SELECT JOUR = CTE_MOIS.JOUR_DEBUT
              FROM CTE_MOIS
            UNION ALL           
            SELECT DATEADD(DAY, 1, CTE_JOUR.JOUR)
              FROM CTE_JOUR
             WHERE MONTH(CTE_JOUR.JOUR) = MONTH(DATEADD(DAY, 1, CTE_JOUR.JOUR)) AND
                DATEADD(DAY, 1, CTE_JOUR.JOUR) <= @FIN
        )
    
        SELECT JOUR
          FROM CTE_JOUR
    )
    

提交回复
热议问题