I had a feeling there was a way to do this without dynamical SQL and Michel figured it out. However, assuming as before that you want only distinct values, that they are not re-used, and that you want it in a function, I believe it can be simplified as demonstrated below.