That's a lot to process without some sample data. You're doing procedural programming in SQL which is optimized for declarative programming. You seem to have more code than what you have shown. I suggest that you give us the complete scenario to be able to help you.