• Take a look at the article by Paul White about APPLY. Half way the article he builds a function from an excisting query. You'll also get other interesting information about using such a function.

    http://www.sqlservercentral.com/articles/APPLY/69953/

    ** Don't mistake the ‘stupidity of the crowd’ for the ‘wisdom of the group’! **