Cannot generate records using Choose(Denali) and Recursive CTE

Question!

I want to generate some records in a recursive CTE using the new choose function

    ;With Cte As
(
    Select 
        Id=1
        To = Cast ('India' as varchar(10))
    Union All
    Select 
        Id +1 
        ,To= Cast( Choose(ID,'India','Belgium') as varchar(10))     
    From Cte 
    Where Id < 10    
)

Select * from Cte

Expected output

Id  PlayerName                  BelongTo
1   Player1                     India
2   Player2                     Belgium    

How can I do so using the Choose function?



Answers

CHOOSE is documented to return NULL:

If the index value exceeds the bounds of the array of values

So you need to perform a modulo operation. The modulo operator in SQL is %, so it would be:

Cast( Choose(((ID%4) 1),'India','Australia','England','Belgium') as varchar(100))

(I initially had a -1 from ID, but given that this statement is executing in a context where the ID value is from the previous row, that's already dealt with)



This video can help you solving your question :)
By: admin