+1  A: 

I'm fairly sure you cannot use dynamic sql in a function.

HLGEM
You are right, sorry
Svetlozar Angelov
Yes, this is true... will likely have to use a stored procedure.
Aaron Bertrand
Thanks everyone for the inputs. Reading the article Aaron suggested helps to clarify. Greetings for all.
byte_slave
+3  A: 

Erland has documented a lot of different ways to accomplish this (but not with functions, as someone else already pointed out), see: http://sommarskog.se/share%5Fdata.html ... may also require reading of his two dynamic SQL articles.

Aaron Bertrand