• You should look at using a stored procedure instead of a function as you are going to need to use dynamic SQL to accomplish this task.  You can't use dynamic SQL in a function.