• Not really looking in detail but

    I think it should be a store procedure.

    And I quite sure we can eliminated the cursor using temp table and update and set variables in a single query.