I just copied your function and it worked. I only added OPTION (MAXRECURSION 32767); in your function but if replacing the function solved the issue then I must had something wrong in implementing your function.

I appreciate all your help.

Thanks for your time and help.