Try to create a primary key/unique key on your table variable, and it is always better to go as a stored proc using temp tables and while loop instead of cursors and try building a clustered index on the temp table which will definitely improve your performance.
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.
Absolutely not. Temp table/While loop replacements for cursors is like smoking a pipe to quit cigars. They're essential identical and a well written firehose cursor (read only, forward only) is frequently faster than the Temp Table/While loop combination. To wit, replacing cursors with While Loops does little to help the situation and will sometimes cause even worse performance because most people aren't good at writing either. ;-)
Please don't make such recommendations in the future because it's a myth and a general bad recommedation to replace cursors with Temp Tables/While loops.
is pronounced ree-bar and is a Modenism for R
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.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Helpful Links:
How to post code problemsHow to post performance problemsForum FAQs