aww,at 1000+ lines of code, without the underlying base tables and linked server(EDWGEARS),
that one is a little bigger scope than i can help with as a volunteer;
it would require substantial testing, i think.
the key, however is to remove the openquery stuff, query the linked server with direct commands, as a set based operation, instead of all those cursors.
you might get rid of the temp tables and replace them with teh direct CTE's as well;
this would be beyond the scope of how i volunteer here, sorry.
--help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!