Question

I'm having a slight bit of trouble with reversing a cursor. I have a ranking of items. If the input is 2, I want to select items 1 and 2, but have it display like this;

RANK
2
1

Right now, when I enter 2, I get

RANK
231
230

Which is the end of the table, instead of the beginning.

My the cursor is just

select rank, item
from itemtable
order by rank desc;

used in the loop like this:

FOR i IN REVERSE 1..v_num LOOP
        DBMS_OUTPUT.PUT_LINE(to_char(v_RANK) || to_char(v_ITEM);            
      FETCH c_rank INTO v_rank, v_item;
        EXIT WHEN c_rank%NOTFOUND;
        END LOOP;

v_num being the number of items to be displayed. I've tried setting the order by to both asc and then desc (like order by rank asc, rank desc) but that didn't work. Reverse doesn't change anything in the output. I've looked at other questions that are similar but wasn't able to find an answer. I'm stumped. This has got to be an easy fix, I just can't seem to figure out what it is.

Was it helpful?

Solution

Assuming that v_num is supposed to be the number of elements that you want returned, it sounds like you'd want to do something like

select *
  from (select rank, item
          from itemtable
         order by rank asc)
 where rownum <= v_num
 order by rank desc

If that's not what you're after, it would be helpful to post a test case (the DDL to create a table, the DML to populate that table, and the expected results) or a link to a fiddle that we can work with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top