You need to put everything inside a string, including the cursor stuff and execute this. See http://www.sommarskog.se/dynamic_sql.html
May I add that dynamic sql + a cursor + a UDF are very likely to kill performance. Also, master.dbo.spt_values isn't fully documented. You'd better use your own number table.
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]