I think what you need is a PIVOT... but it isn't that simple. Pivots work best when the col names are known. It's possible to pivot on dynamic columns, but you also still have to know how many ... which can be a bit tricky.
That said, anything you're doing, isn't going to be viable in a function. An SProc, sure, but not a function.

theCursor doesn't need the @ because it isn't a variable. It's a pointer to the table. It essentially becomes an object itself.

-tg