Hey Swaroop,
Before correcting your procedure, If I understand your scenario properly it can be easily achieved using Window Functions like Rank() , Also this can be achieved via modeller too
See an example scenario below:
For each Region and for each country , I need top 2 employees based on salaries: ( Similar to your scenario )
SELECT "REGION","COUNTRY","EMPLOYEE NAME","SALARY" FROM (SELECT "REGION","COUNTRY","EMPLOYEE NAME","SALARY",RANK() OVER (PARTITION BY "REGION","COUNTRY" ORDER BY SALARY DESC) AS RANK FROM EMPLOYEE) WHERE RANK <= 2 ORDER BY "REGION","COUNTRY"
Output:
For more details on the table and data i used, have a look on this blog:
Let us try achieving this without using dynamic sql or cursors
Let me know your thoughts.
Regards,
Krishna Tangudu