• I would use a persistent temp table rather than a table variable for your purpose.

    Basically you need to clear the temp table, insert records, and then use Sean's function to get the result.

    Table variable is difficult to maintain (making a change) and its performance is another concern.