I'm fairly sure you cannot use dynamic sql in a function.
HLGEM
2009-10-20 13:55:53
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.