• But I don't think this is correct way creating tables and dropping tables and selecting data twice

    It's fine the way it is except for the drops at the end. No need for those.

    The only data you're selecting more than once is the data that's actually being returned and that will be quite small compared to what's in the log.

    I suppose you could use OPENROWSET to execute the xp directly for such a thing but that's probably a level of sophistication that won't be worth it here.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)