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

后端 未结 6 1487
粉色の甜心
粉色の甜心 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:23

    create simple sample for you :)

    /* block create function for test in sql*/
    /*FUNCTION [fn_CTE_withLevel] (@max_level int)
    RETURNS TABLE
      AS
     RETURN  
           ( */
    
    
     /*******************   declare table just replace real table   *****/
    declare @tbl table(pid varchar(15),id varchar(15))
    
    /* use function argument */
    declare @max_level int = 3
    
    Insert Into @tbl(pid , id)
       values 
    
         /*lev1*/   ('0','1') ,
             /*lev2*/   ('1','101') ,
             /*lev2*/   ('1','102') ,
         /*lev1*/   ('0','2') ,
             /*lev2*/   ('2','201') ,
                     /*lev3*/   ('201','20101') ,
                     /*lev3*/   ('201','20102') ,
             /*lev2*/   ('2','202') ,
         /*lev1*/   ('0','3') ,
             /*lev2*/   ('3','301') ,
             /*lev2*/   ('3','302') ,
         /*lev1*/   ('0','4') ,
            /*lev2*/    ('4','401'),
            /*lev2*/    ('4','402');
    
     /*******************   declare table just replace real table   *****/
    
      With cte_result(pid , id , lev)
            As(
                Select pid , id , 1 as lev From @tbl t
                  Where pid = '0'  /* change to another values from list to test sub items */
    
                  Union All
    
                Select t.pid , t.id , cte.lev + 1 as lev
                     From  cte_result cte
                            inner Join  @tbl t
                      On  cte.id = t.pid 
                       Where cte.lev < @max_level  -- :) this is my idea
              )
    
             Select * From cte_result 
                 --OPTION (MAXRECURSION 100)
    
      -- uncomment for create function
     /*)*/
    

提交回复
热议问题