>>So, I recommend to lean towards stored procedures for complex logic and not try to abuse functions (although, of course, they do have their place).
>
>so are you saying the code I wrote would work in an SP?
I haven't studied your code in details, but generally, yes.
If it's not broken, fix it until it is.
My Blog